使用 Rails 3.2.11 和 ruby 1.9.3:
我有 Review、User 和 ReviewAccess 类
class ReviewAccess < ActiveRecord::Base
belongs_to :user
belongs_to :review
attr_accessible :role_id
end
class Review < ActiveRecord::Base
has_one :review_accesses_owner, :class_name => 'ReviewAccess',
:conditions => "review_accesses.role_id = 1"
has_one :owner, :class_name => 'User', :through => :review_accesses_owner,
:source => :user
end
基本上 Review 与 User 是多对多的,连接表是 ReviewAccess,它在 role_id 列中还包含关系角色(所有者为 1)。我可以通过以下方式阅读评论所有者:
Review.owner # works
# sql: SELECT "review_accesses".* FROM "review_accesses" WHERE "review_accesses"."review_id" = 7 AND (review_accesses.role_id = 1) LIMIT 1
但是,设置所有者不起作用,因为它没有将 role_id 设置为 1(如关联的条件子句中所述)
Review.owner = current_user # does not set role_id
# sql: INSERT INTO "review_accesses" ("created_at", "review_id", "role_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["created_at", Sun, 27 Oct 2013 08:02:54 UTC +00:00], ["review_id", 7], ["role_id", nil], ["updated_at", Sun, 27 Oct 2013 08:02:54 UTC +00:00], ["user_id", 1]]
我知道我可以覆盖 owner= 但我有很多(对于每个角色),我想改用关联 DSL。
如何更新有条件的关联以设置创建条件?