使用带有两个键的 ActiveRecord own_to
我有两个具有 hasMany/belongsTo 关联的 ActiveRecord 模型:
class User < ActiveRecord::Base
has_many :letters
end
class Letter < ActiveRecord::Base
belongs_to :user
end
User 模型有一个 revision_number 属性,我希望将其范围限定在 own_to 关联中,因此该字母通过 user.id 和 user.revision_number 与用户关联。
我尝试使用 API 文档中记录的 :conditions 键:
class Letter < ActiveRecord::Base
belongs_to :user, :conditions => "revision_number = #{client_revision}"
end
但这尝试在 Letter 类上调用 client-revision,而不是 Letter 的实例。 谁能指出我正确的方向来正确确定belongs_to关联的范围?
我正在使用 acts-as-revisable 插件来版本化用户模型。
I have two ActiveRecord models with a hasMany / belongsTo association:
class User < ActiveRecord::Base
has_many :letters
end
class Letter < ActiveRecord::Base
belongs_to :user
end
The User model has a revision_number attribute, to which I would like to scope the belongs_to association, so the letter is associated to a User by both user.id and user.revision_number.
I tried using the :conditions key as documented in the API docs:
class Letter < ActiveRecord::Base
belongs_to :user, :conditions => "revision_number = #{client_revision}"
end
but this attempts to call client-revision on the Letter class, not the instance of Letter. Could anyone point me in the right direction for scoping the belongs_to association correctly?
I'm using the acts-as-revisable plugin to version the User model.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我很难理解为什么您希望以这种方式确定
belongs_to
的范围。 如果我错了,请纠正我,但这样做可能会更好。 我假设你想要某种版本控制系统:I am having a hard time understanding why you would want to scope the
belongs_to
in this way. Correct me if I am wrong, but it might be better to do something like this. I am assuming you want some sort of version control system:最后发现我需要的是复合键之类的东西,Rails ActiveRecord 不支持它。 解决方案(至少现在)是在 Letter 上编写自定义客户端访问器以支持复合键(id 和 revision_number):
通过此设置,Client#1.letters 将检索两个字母的数组,但 Letter#2 除外。 client 将检索 Client#1r2,而 Letter#2.client 将检索 Client#1r4:
仍然不确定这是否是解决此问题的最佳方法,但目前似乎有效。
Finally figured out what I needed was something like composite keys, which Rails ActiveRecord doesn't support. The solution (for now at least) was to write custom client accessors on the Letter to support the composite keys (id and revision_number):
With this setup, Client#1.letters will retrieve an array of both letters, but Letter#2.client will retrieve Client#1r2, whilst Letter#2.client will retrieve Client#1r4:
Still not sure if this is the best approach to this problem, but it seems to work for now.