我正在使用Rails 4/5中的嵌套表单。在Rails4中使用@my_model_instance.build
的代码似乎在Rails 5中不起作用。我不确定这是一个错误还是我的错
详细信息:
Rails 4.2.3控制台:
> @item = ItemType.new
=> #<ItemType id: nil, name: nil, .... >
> @item.item_abilities
=> #<ActiveRecord::Associations::CollectionProxy []>
> @item.item_abilities.build
=> #<ItemAbility id: nil, item_type_id: nil, ... >
> @item.item_abilities
=> #<ActiveRecord::Associations::CollectionProxy [#<ItemAbility id: nil, item_type_id: nil, ... ]>
这符合记录/预期。现在让我们在Rails 5(rc2)中的相同代码库上尝试相同的东西。
Rails 5.0.0rc2 console:
> @item = ItemType.new
=> #<ItemType id: nil, name: nil, .... >
> @item.item_abilities
=> #<ActiveRecord::Associations::CollectionProxy []>
> @item.item_abilities.build
ArgumentError: wrong number of arguments (given 2, expected 0..1)
from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.rc2/lib/active_record/core.rb:312:in `initialize'
from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.rc2/lib/active_record/inheritance.rb:65:in `new'
from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.rc2/lib/active_record/inheritance.rb:65:in `new'
from /var/lib/gems/2.3.0/gems/protected_attributes-1.1.3/lib/active_record/mass_assignment_security/reflection.rb:8:in `build_association'
from /var/lib/gems/2.3.0/gems/protected_attributes-1.1.3/lib/active_record/mass_assignment_security/associations.rb:7:in `build_record'
from /var/lib/gems/2.3.0/gems/protected_attributes-1.1.3/lib/active_record/mass_assignment_security/associations.rb:25:in `build'
from /var/lib/gems/2.3.0/gems/protected_attributes-1.1.3/lib/active_record/mass_assignment_security/associations.rb:64:in `build'
from (irb):2
from /var/lib/gems/2.3.0/gems/railties-5.0.0.rc2/lib/rails/commands/console.rb:65:in `start'
from /var/lib/gems/2.3.0/gems/railties-5.0.0.rc2/lib/rails/commands/console_helper.rb:9:in `start'
from /var/lib/gems/2.3.0/gems/railties-5.0.0.rc2/lib/rails/commands/commands_tasks.rb:78:in `console'
from /var/lib/gems/2.3.0/gems/railties-5.0.0.rc2/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
from /var/lib/gems/2.3.0/gems/railties-5.0.0.rc2/lib/rails/commands.rb:18:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
这是我正在做的事情,还是Rails5疯了?
模型的相关部分:
item_type.rb
class ItemType < ActiveRecord::Base
## Relationships
belongs_to :item_collection
has_many :item_abilities
has_many :item_instances
accepts_nested_attributes_for :item_abilities
...
end
item_instance.rb
class ItemAbility < ActiveRecord::Base
# Relationships
belongs_to :item_type
...
end
Ruby版本:
ruby 2.3.1p112 (2016-04-26) [x86_64-linux-gnu]
答案 0 :(得分:0)
这是protected_attributes
宝石,仍然在Rails 3&gt; 4天左右徘徊,导致上述问题。
我在protected_attributes
gem网站上发布了一个错误,他们回答说Rails 5不支持gem。
如果其他人有这个问题,那么Rails&#39;适当的&#39;可以在此处找到解决此问题的方法:How is attr_accessible used in Rails 4?或此处:http://api.rubyonrails.org/classes/ActionController/StrongParameters.html
感谢@oreoluwa指出我正确的方向