【问题标题】:Creating new model instance with paramethers (Rails)使用参数创建新模型实例(Rails)
【发布时间】:2015-09-07 11:11:46
【问题描述】:

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

事件.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#create 中的 ActionController::ParameterMissing

【问题讨论】:

    标签: ruby-on-rails post routing params


    【解决方案1】:

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

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

    更多详情请阅读'strong parameters' gem documentation

    【讨论】:

    • 这也不好用,但谢谢你的链接。
    【解决方案2】:

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

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

    【讨论】:

    • 真的吗?这不太可能是真的。你能删除to_i 并重新检查吗?我确定这是因为没有event 键。
    猜你喜欢
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2013-02-11
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    相关资源
    最近更新 更多