1

我正在使用 Rails 4 / 5 中的嵌套表单@my_model_instance.build。Rails4 中使用的代码似乎在 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 控制台:

> @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 2.3.1p112 (2016-04-26) [x86_64-linux-gnu]
4

1 回答 1

0

这是protected_attributes宝石,仍然在 Rails 3-> 4 天里徘徊,导致了上述问题。

我在 gem 网站上发布了一个错误protected_attributes,他们回应说 Rails 5 不支持 gem。

如果其他人有这个问题,可以在这里找到解决此问题的 Rails“正确”方法:如何在 Rails 4 中使用 attr_accessible?或在这里:http ://api.rubyonrails.org/classes/ActionController/StrongParameters.html

感谢@oreoluwa 为我指明了正确的方向

于 2016-06-28T19:07:55.673 回答