gpt4 book ai didi

ruby-on-rails-3 - 导轨 : Belongs_to Polymorphic Association + conditions

转载 作者:行者123 更新时间:2023-12-02 01:44:27 25 4
gpt4 key购买 nike

所以我有这个模型:

class Model < ActiveRecord::Base
attr_accessible :to_id, :to_type

belongs_to :to, polymorphic: true

end

我想知道当belongs_to 处于特定类型时是否可以添加另一个关系:
class Model < ActiveRecord::Base
attr_accessible :to_id, :to_type

belongs_to :to, polymorphic: true
belongs_to :to_user, :foreign_key => :to_id, :conditions => ['to_type = ?', 'User'] # doesn't work
# OR MAYBE
belongs_to :to_user, :foreign_key => :to_id, :foreign_class => 'User' # It doesn't check on Model's to_type...
end

所以 my_model.to_user将返回 user如果存在,和 nil如果未设置或属于不同类别。

使用 Rails 3.2

谢谢!

最佳答案

你可以在里面使用 where 条件,比如

 belongs_to :to_user,-> {where(:to_type=> 'User')},  :foreign_key => :to_id

表格更多看看这个 association callbacks

关于ruby-on-rails-3 - 导轨 : Belongs_to Polymorphic Association + conditions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26544310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com