【问题标题】:Building associations in a before-filter in rails4在 rails4 的前置过滤器中建立关联
【发布时间】:2013-06-09 15:50:35
【问题描述】:

我正在将应用程序从 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

上面的代码在 rails3 中工作,但在 rails4 中创建了空记录。控制台中的一些尝试和错误表明,确实没有分配属性。

f = Foo.new
f.bars.build({name: 'Bar'})
 => #<Bar id: nil, name: nil>

建立关联并将它们与其父记录一起保存的正确方法是什么?

【问题讨论】:

  • 这可能与attr_accessible被强参数替换有关。

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

我认为@Mischa 是对的。我一直在将我的应用程序迁移到 rails4 并且它可以工作:

user.authorizations.build provider: "bla"
=> #<Authorization id: nil, provider: "bla", uid: nil, user_id: 1, created_at: nil, updated_at: nil>

你可以看看我所做的更改:https://github.com/phoet/on_ruby/pull/83/files#L23L59

很可能它正在删除:

# Mass assignment settings
config.active_record.whitelist_attributes = true

【讨论】:

  • 很好的提示,但我在迁移时删除了该部分。
  • @pduersteler 你还在使用带有向后兼容 gem 的 attr_accessible 吗?
  • 不,没有向后兼容的 gem,也没有定义 attr_*(期望访问者)。如果我定义例如attr_accessible,我收到一个错误。
  • 什么都没有。我想我会生成一个干净的 rails4 骨架并移动所有与应用程序相关的代码。
  • 你试过运行 rake rails:upgrade 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多