【问题标题】:Rails has_many :through with :conditions . How do I create the associations?Rails has_many :through 和 :conditions 。如何创建关联?
【发布时间】:2012-09-18 01:58:42
【问题描述】:

我有以下通过条件与 has_many 关联的模型。

(注意Membership 验证kind 属性的存在)

class User < ActiveRecord::Base
  has_many :memberships
  has_many :founded_groups,
    :through => :memberships,
    :source  => :group,
    :class_name => 'Group'
    :conditions => {'memberships.kind' => 'founder'}
  has_many :joined_groups, ... # same as above, but the kind is 'member'
end

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :founders, ...        # these two mirror the User's
  has_many :regular_members, ... #
end

class Membership < ActiveRecord::Base
  validates_presence_of :user_id
  validates_presence_of :club_id
  validates_presence_of :kind   # <-- attention here!

  belongs_to :user
  belongs_to :group
end

Rails 似乎喜欢上面的代码(至少它不喜欢它)。但后来发生了这种情况:

> user = User.create(...) # valid user
> club = Club.create(...) # valid club
> user.founded_clubs = [club]

ActiveRecord::RecordInvalid: Validation failed: kind can't be blank

> club.founders << user

ActiveRecord::RecordInvalid: Validation failed: kind can't be blank

我假设 rails 会采用我的代码的 {'memberships.kind' =&gt; 'founder'} 部分并在创建关联时使用它,但似乎并非如此。所以新成员的kind 是空白的,这会引发错误。

有没有一种简单的方法来创建关联,而不是完全痛苦?

【问题讨论】:

    标签: ruby-on-rails ruby has-many-through has-many


    【解决方案1】:

    这肯定会起作用:

    > user = User.create(...) # valid user
    > club = Club.create(...) # valid club
    > user.memberships.create(:club_id => club.id, :kind => 'founder')
    

    我不确定,但这可能有效:

    > user.memberships.create(:club => club, :kind => 'founder')
    

    【讨论】:

    • 谢谢。我希望找到某种语法,允许我在给定多个元素的情况下创建会员资格——一个俱乐部和两个用户,或者一个用户和两个俱乐部。看来我只需要遍历“许多”部分并手动创建关联。哦,好吧。
    猜你喜欢
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 2014-02-27
    • 1970-01-01
    相关资源
    最近更新 更多