Rails& strong_parameters'缺少必需参数'

时间:2014-03-07 07:04:21

标签: ruby-on-rails parameters strong-parameters

我正在为我的一个项目创建'转发'(restream)功能,但我一直遇到这个错误:

Required parameter missing: restream

我不确定我在这里缺少什么。这是我的设置。有什么想法吗?

模型

#app/models/member.rb
Class Member < ActiveRecord::Base
    has_many :statuses
end

#app/models/status.rb
Class Status< ActiveRecord::Base
    belongs_to :member
    has_many :restreams, class_name: "Status", foreign_key: "restream_id"
end

Restream

#config/routes.rb
resources :statuses do
    member do
        post :retweet
    end
end

#app/controllers/statuses_controller.rb
def restream
    @restream = Status.new(restream_params)
    @restream.save
end

private

def restream_params
    params.require(:restream).permit(:restream_id, :content).merge(member_id: current_user.id)
end

#app/views/statuses/show.html.erb
<%= link_to image_tag("Re-Stream 3.png", class: "act_actions", title: "Restream", alt: "Restream"), restream_status_path(status.id), method: :post, :class => "btn restream" %>

2 个答案:

答案 0 :(得分:0)

您需要传递restream param。您还需要在get中发送它,并指定restream_param的值,因为它是link_to.

#app/views/statuses/show.html.erb
<%= link_to image_tag("Re-Stream 3.png", class: "act_actions", title: "Restream", alt: "Restream"), restream_status_path(status.id), params.merge({:restream => "the value you want to pass"})  method: :get, :class => "btn restream" %>

答案 1 :(得分:0)

查看params hash in rails

可以最好地解释您的错误

示例

  

{“company”:{“name”:“acme”,“address”:“123 Carrot Street”}}

     

你会得到params [:company]为{“name”=&gt; “acme”,“address”=&gt; “123   胡萝卜街“}


强大的参数

要使strong_params正常工作,您的参数哈希需要如下所示:

{ "restream": {"your":"params", "go":"here"} }

问题是你的params哈希看起来像这样:

{"your":"param", "goes":"here"}

<强>修正

有两种方法可以解决这个问题:

def restream_params
    params.permit(:restream_id, :content).merge(member_id: current_user.id)
end

这将允许:restream_id:content params,而无需将它们嵌入params散列的:restream选项中

另一种选择是通过您的链接传递:restream参数。 Sidney的回答非常好,但我会使用form_for,因为我知道这会根据需要设置params哈希:

<%= form_for @restream %>
    <%= text_field :restream_id %>
<% end %>