简体   繁体   中英

Rails 3 - associations “through” - how to get the data from DB?

I have a problem with fetching data from DB, where is between models association kind through .

On my site, I have a categories, like a sports, news, weather etc. When an user is logged in and has a selected the categories, from which want to see the articles, then I would like to display only these articles.

Here's how looks like my models:

class User < ActiveRecord::Base
  has_many :user_categories
  has_many :categories, :through => :user_categories
end

class Category < ActiveRecord::Base
  has_many :articles

  has_many :user_categories
  has_many :users, :through => :user_categories
end


class UserCategory < ActiveRecord::Base
  belongs_to :user
  belongs_to :category
end

class Article < ActiveRecord::Base
  belongs_to :category
end

But I still can't find the way, how to get all articles from user's selected categories... I tried something like

Article.joins("LEFT JOIN categories ON category.id = user_categories.category_id").where('user_categories.user_id = ?', current_user.id)

I would grateful for every advice!

Thank you

Here's one way to do it:

Article.where(:category_id => current_user.categories.map {|c| c.id})

That will create 2 queries. First one will return a list of the current user's categories. Then the ruby map function will create an array containing the ids of those categories. The second query will then return a list of articles whose category_id is in the array of ids. The second query will look something like:

select articles.* from articles where articles.category_id in(1,2,3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM