Ruby on rails 在rails4中的前置过滤器中构建关联
我正在将应用程序从rails3.2.13迁移到rails4.0.0-rc1。我有以下代码:Ruby on rails 在rails4中的前置过滤器中构建关联,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我正在将应用程序从rails3.2.13迁移到rails4.0.0-rc1。我有以下代码: class Foo < ActiveRecord::Base has_many :bars before_create :build_bars private def build_bars self.bars.build({name: 'Bar 1'}) self.bars.build({name: 'Bar 2'}) end end class Foo #
class Foo < ActiveRecord::Base
has_many :bars
before_create :build_bars
private
def build_bars
self.bars.build({name: 'Bar 1'})
self.bars.build({name: 'Bar 2'})
end
end
class Foo
上面的代码在rails3中工作,但在rails4中创建空记录。控制台中的一些try&error显示,确实没有分配属性
f = Foo.new
f.bars.build({name: 'Bar'})
=> #<Bar id: nil, name: nil>
f=Foo.new
f、 build({name:'Bar'})
=> #
建立关联并将其与父记录一起保存的正确方法是什么?我认为@misha是正确的。我一直在将我的应用程序迁移到rails4,它可以工作:
user.authorizations.build provider: "bla"
=> #<Authorization id: nil, provider: "bla", uid: nil, user_id: 1, created_at: nil, updated_at: nil>
这可能与将
attr\u accessible
替换为强参数有关。提示很好,但我在迁移时删除了该部分。@pduerstler您是否仍在使用attr\u accessible和向后兼容的gem?不,没有向后兼容的gem,也没有定义attr\u*
(除访问器外)。如果我定义了例如attr_accessible,我会得到一个错误,什么都没有。。我想我将生成一个干净的rails 4框架,并浏览所有与应用程序相关的代码。您是否尝试运行rake rails:upgrade?
# Mass assignment settings
config.active_record.whitelist_attributes = true