强大的参数,嵌套属性:无法进行质量分配

时间:2015-12-15 08:51:53

标签: ruby-on-rails

我使用Rails 4.0.2并且无法获得强参数来处理嵌套属性。

# Model
has_one :availability
accepts_nested_attributes_for :availability

# Controller
def base_content_params
 params.require("base_content").permit(:enabled, :language, :title, :description,
      availability_attributes: [:duration, :slots])
end

# View
form_for [app, base_content] do |form|
  form.fields_for :availability do | a |
    a.select 'duration', duration_values
  end

  form.fields_for :availability do | a |
    a.select 'slots', [*(1..10)]
  end

但我一直在接受:

Can't mass-assign protected attributes for BaseContent: availability_attributes

>> base_content_params
=> {"enabled"=>"false", "title"=>"test", "description"=>"", availability_attributes"=>{"duration"=>"30", "slots"=>"10"}}

# request parameters    
{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"---", "base_content"=>{"enabled"=>"false", "language_id"=>"12938", "title"=>"test", "description"=>"", "content"=>"", "terms"=>"", "category"=>"product", "category_mode"=>"appy_booking", "responder_email"=>"", "price"=>"111.00", "price_per"=>"unit", "availability_attributes"=>{"start_at(5i)"=>"17:45:00", "id"=>"1", "duration"=>"30", "slots"=>"10"}, "reward_points"=>"100", "hash_tags"=>"", "lat"=>"", "lng"=>""}, "commit"=>"Save & Continue edit", "geocoder_lat"=>"0.0", "geocoder_lng"=>"0.0", "pac-input"=>"", "action"=>"update", "controller"=>"backend/base_contents", "app_id"=>"1898", "id"=>"16108"}

我在这里缺少什么?

修改

# BaseContent Model

class BaseContent < ActiveRecord::Base
   attr_accessible :enabled, :price, :price_per, :app, :menu, 

# App Model
class App < ActiveRecord::Base
  attr_accessible :name, :allow_search, :display_logo_badge, #... etc

1 个答案:

答案 0 :(得分:1)

这应该是一个评论,但它太长了。

从您的评论中,现在问题就更清晰了。如果您使用的是Rails 4.0.2,则必须切换到使用控制器中的strong_params

#app/controllers/your_controller.rb
class YourController < ApplicationController
   def create
      @model = Model.new model_params
      @model.save
   end

   private

   def model_params
     params.require(:model).permit(:attribute1, :attribute2)
   end
end

强烈建议您浏览模型,删除所有attr_accessible引用,删除protected_attributes gem并重建强大参数的功能。

-

我可以看到的另一个问题是你打电话给你的表格:

form_for [app, base_content] do |form|

为什么要在base_content下嵌套app(应该是一个实例变量)?如果有的话,我会期待某些事情......

form_for @base_content do |form|