【问题标题】:find_or_create_by on intermediate table in rails 2.3在rails 2.3的中间表上find_or_create_by
【发布时间】:2014-03-10 17:22:36
【问题描述】:

我有 2 个表,与下面的第三个表相关。

class A < ActiveRecord::Base
  has_many :B, :through => :AB
  has_many :AB
end

class B < ActiveRecord::Base
  has_many :A, :through => :AB
  has_many :AB
end

class AB < ActiveRecord::Base
  belongs_to :B,
  belongs_to :A
end

我希望能够使用 find_or_create 插入中间表 (AB)。但是 find_or_create 在 AB 上不起作用。除了单独查找和创建之外,我该怎么做??

PS:我不想使用 has_and_belongs_to_many 因为它不会创建中间模型,我想插入中间表而不在最终表 A 和 B 中创建任何额外的行。

请给点建议??

【问题讨论】:

  • 你遇到了什么错误?

标签: ruby associations ruby-on-rails-2


【解决方案1】:

find_or_create_by已经添加到rails 4中,你可以自己写(应该去初始化器):

class ActiveRecord::Base
  def self.find_by(params)
    scoped.where(params).limit(1).first
  end

  def self.find_or_create_by(params)
    find_by(params) || create(params)
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2011-03-04
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    相关资源
    最近更新 更多