使用参数(Rails)创建新模型实例

时间:2015-09-07 11:11:47

标签: ruby-on-rails post routing params

我需要从用户的访客页面创建新事件,而Event.visitor_id应该是User.id

Event.rb

def create
@event = current_user.owner_events.new(event_params)
end

protected

def event_params
params.require(:event).permit(:visitor_id)
end

我需要更正下面无效的视图:

<%= link_to "Create event with this user", events_path(visitor_id: @user.id), method: :post %>

我得到:EventController :: ParametersMissing在EventsController #create

2 个答案:

答案 0 :(得分:1)

试试(你忘了添加event键):

<%= link_to "Create event with this user", events_path(event: { visitor_id: @user.id }), method: :post %>

有关详细信息,请参阅'strong parameters' gem documentation

答案 1 :(得分:0)

我只需要将.to_i添加到@ user.id

<%= link_to "Create event", events_path(:event =>{:visitor_id => @user.id.to_i} ), :method => :post %>