开发者

I need help with a Rails ActiveRecord Join - I know how to do it in SQL

I have 2 tables I need to join but the user_id column value is not the same in both tables. So I want to do something like this:

In my controller 4 will be substituted with current_user.id

select * from sites join pickups on sites.id = pickups.site_id where sites.user_id = '4'

But using an ActiveRecord Find.

Here are my associations:

class Site < ActiveRecord::Base
  belongs_to :user
  has_many :pickups

class Pickup < ActiveRecord::Base  
 belongs_to :site   
 belongs_to :user

class User < ActiveRecord::Base
    has_one  :profile
    has_many :pickups
    has_many :开发者_C百科sites

Thanks in advance!


If you add this to your user model:

has_many :site_pickups, :through => :sites, :source => :pickups

You can do

current_user.site_pickups


try this:

sites = current_user.sites.find(:all, :include => [:pickup])
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜