开发者

Rails/ActiveRecord: joining first association only

开发者 https://www.devze.com 2023-04-13 08:55 出处:网络
class Session has_many :events end class Event belongs_to :session # r开发者_StackOverfloweferrer column
class Session
  has_many :events
end

class Event
  belongs_to :session

  # r开发者_StackOverfloweferrer column
end

Each event has a referrer column, but I'm only interested in the original (first) referrer for the session. So I'd like to be able to join the first event to the session. Is this possible with ActiveRecord?

EDIT:

To clarify, I'd like to pull a list of sessions and join the sessions' events. However, rather than joining ALL of the events, I'd like just the FIRST event (as in the first created).

Session.joins(:events) # but I don't want to join all events, just the first one, so I can access the first event's referrer column.


Of cause thats possible. What you need is a foreign key in the events table. That should be called session_id and it will automaticly be set when you pass by a session. Like that:

event.session=Session.first

To add a session_id column to the events table you need to generate a migration

rails g migration addSessionIdToEvents

And add a column...

def self.up<br />
  add_column :events, :session_id, :integer<br />
end

And then migrate it

rake db:migrate
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号