我开发了一个应用程序,用户可以登录并查看他们的活动。可以单击该事件,并在事件显示页面中添加歌曲。我遇到的问题是,当您在填写歌曲字段后单击提交时,它会给我一个错误,因为它无法找到歌曲添加到的事件ID。我已经在我的方法中定义了一个current_event变量,但仍然没有运气:(。我觉得一旦我可以通过这个我的应用程序将起作用,我不需要问这么多关于这个特定的应用程序的问题大声笑。 这是我的歌曲控制器:
class SongsController < ApplicationController
def create
current_event = Event.find(params[:event_id])
@song = current_event.songs.build(songs_params)
if @song.save
flash[:success] = "Success"
redirect_to root_url
else
flash[:error] = "Fail"
end
end
def destroy
end
private
def song_params
params.require(:song).permit(:artist, :title, :genre)
end
end
歌曲形式:
<%= form_for Song.new do |f| %>
<%= f.text_field :artist %>
<%= f.text_field :title %>
<%= f.text_field :genre %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
路线:
Rails.application.routes.draw do
root 'welcome#index'
get '/signup', to: 'users#new'
get '/signup', to: 'users#create'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'
get '/account', to: 'users#show'
resources :users
resources :events
resources :songs
end
再次感谢所有人的帮助和支持:D
答案 0 :(得分:1)
您需要以下列形式传递您的活动ID:
<%= form_for Song.new do |f| %>
<%= f.hidden_field :event_id, value: @event.id %> #assuming you have @event defined in show action
<%= f.text_field :artist %>
<%= f.text_field :title %>
<%= f.text_field :genre %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
在您的控制器中:
class SongsController < ApplicationController
def create
current_event = Event.find(micropost_params[:event_id])
@song = current_event.songs.build(songs_params)
if @song.save
flash[:success] = "Success"
redirect_to root_url
else
flash[:error] = "Fail"
end
end
def destroy
end
private
def micropost_params
params.require(:song).permit( :event_id,:artist, :title, :genre)
end
end