Ruby on rails Rails在连接模型中有很多:通过Find by额外属性
Ruby和Rails都是新手,但我现在已经接受了书本教育(这显然毫无意义,哈哈) 我有两个模型,Event和User通过表EventUser连接Ruby on rails Rails在连接模型中有很多:通过Find by额外属性,ruby-on-rails,ruby,has-many,has-many-through,Ruby On Rails,Ruby,Has Many,Has Many Through,Ruby和Rails都是新手,但我现在已经接受了书本教育(这显然毫无意义,哈哈) 我有两个模型,Event和User通过表EventUser连接 class User < ActiveRecord::Base has_many :event_users has_many :events, :through => :event_users end class EventUser < ActiveRecord::Base belongs_to :event bel
class User < ActiveRecord::Base
has_many :event_users
has_many :events, :through => :event_users
end
class EventUser < ActiveRecord::Base
belongs_to :event
belongs_to :user
#For clarity's sake, EventUser also has a boolean column "active", among others
end
class Event < ActiveRecord::Base
has_many :event_users
has_many :users, :through => :event_users
end
因为事件实际上没有额外的数据,所以EventUser模型有。虽然我能做到:
u = User.find :first
active_events = []
u.event_users.find_by_active(true).do |eu|
active_events << eu.event
end
u=User.find:第一个
活动_事件=[]
u、 事件_用户。按_活动查找_(真)。执行| eu|
活动事件在用户模型中添加类似的内容如何
has_many :active_events, :through => :event_users,
:class_name => "Event",
:source => :event,
:conditions => ['event_users.active = ?',true]
之后,您只需调用以下命令,就可以为用户获取活动事件:
User.first.active_events
User.first.active_events
即使您的u.events没有显式调用user_events表,但由于必要的联接,该表仍然隐式包含在SQL中。因此,您仍然可以在查找条件中使用该表:
u.events.find(:all, :conditions => ["user_events.active = ?", true])
当然,如果您计划经常进行此查找,那么请确定,按照米兰诺沃塔的建议,给它一个单独的关联,但不要求您这样做米兰诺沃塔有一个很好的解决方案–但是:conditions
现在已被弃用,:conditions=>['event\u users.active=?',true]
bit无论如何看起来都不太适合rails。我喜欢这样的东西:
u = User.find :first
active_events = u.events.find_by_active(true)
has_many :event_users
has_many :active_event_users, -> { where active: true }, class_name: 'EventUser'
has_many :active_events, :through => :active_event_users, class_name: 'Event', :source => :event
在此之后,您仍然可以通过调用以下命令为用户获取活动事件:
User.first.active_events
User.first.active_events
嗯,用户
模型承担的责任比实际需要的要多,而且没有很好的理由这样做
我们可以首先在EventUser
模型中定义范围,因为它实际上属于什么地方,比如:
class EventUser < ActiveRecord::Base
belongs_to :event
belongs_to :user
scope :active, -> { where(active: true) }
scope :inactive, -> { where(active: false) }
end
这种技术的美妙之处在于,作为活动或非活动事件的功能属于EventUser
模型,如果将来需要修改该功能,它将只在一个地方进行修改:EventUser
模型,并且这些更改将反映在所有其他模型中。我已经为您做了标记,但是,如果我早上没有得到更好的答案,那就是你的了。请参阅下面我的答案,了解更为最新的方法。谢谢,Rails 4 way是:->{where event_users:{active:true}}
,但条件不可能由event_users
范围定义?比如作用域:active,其中(:active=>true)
?(使用Rails 3.2)@IvanBlack您能解释一下在has\u many through:
?你能包括整个Rails 4特定的等价物吗?我喜欢在一个地方定义所有范围-在模型中,即使我只使用一次。它使我的控制器精简,整体设计更加一致。您还可以使用Gareth的建议创建一个命名范围。如果您还没有使用Rails 4,您仍然可以遵循这个优秀的示例,但您可能需要使用不推荐的:conditions=>{active:true}
。为我工作,谢谢!你的解决方案让我大吃一惊:)