Rails 4,强参数,嵌套资源,构建和未定义方法允许

时间:2014-01-18 21:25:26

标签: ruby-on-rails-4 strong-parameters nested-resources

我无法通过构建获得rails 4,强大的参数来处理嵌套资源。任何建议都会非常受欢迎。

RSPEC向我展示

创建操作创建操作      失败/错误:click_button“创建操作”      NoMethodError:        未定义的方法permit' for "create":String # ./app/controllers/actions_controller.rb:24:in action_params'      './app/controllers/actions_controller.rb:10:in create' # ./spec/features/creating_actions_spec.rb:16:in块(2级)in'

我的浏览器向我显示:

ActionsController中的NoMethodError #create undefined方法`permit'for“create”:String

提取的来源(第24行):

def action_params     params.require(:action).permit(:title,:description)   端

操作控制器包含:

def create
    @action = @project.actions.build(action_params)
    if @action.save
        flash[:notice] = "Action has been created."
        redirect_to [@project, @action]
    else
        flash[:alert] = "Action has not been created."
        render "new"
    end
end
private

def action_params
  params.require(:action).permit(:title, :description)
end

我使用的是嵌套资源:

resources :projects do
  resources :actions
end

表单如下:

<%= form_for [@project, @action] do |f| %>
<% if @action.errors.any? %>
<div id="error_explanation" >
  <h2><%= pluralize(@action.errors.count, "error") %>
  prohibited this action from being saved:</h2>

  <ul>
  <% @action.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
</ul>
 </div>
  <% end %>

 <p>
   <%= f.label :title %><br>
   <%= f.text_field :title %>
  </p>

  <p>
   <%= f.label :description %><br>
   <%= f.text_area :description %>
 </p>
 <%= f.submit %>
 <% end %>

1 个答案:

答案 0 :(得分:7)

这种情况正在发生,因为Rails默认发送包含所请求操作的:action参数。执行params.require(:action)时,您实际上会将请求的操作名称作为字符串返回,在这种情况下,创建。您可以明确告诉form_for使用另一个密钥作为哈希,解决您的强参数问题:

<%= form_for [@project, @action], as: :foo do |f| %>

在你的控制器中:

params.require(:foo).permit...