dimanche 23 août 2015

Accessing objects from many to many join table - RAILS

In ActiveRecord/Ruby on Rails if i have a many-to-many relationship set up like so:

class Blog < ActiveRecord::Base
  has_many :tagged_blogposts;
  has_many :tags, through: :tagged_blogposts;
end

class Tag < ActiveRecord::Base
  has_many :tagged_blogposts
  has_many :blogs, through: :tagged_blogposts
end

class TaggedBlogpost < ActiveRecord::Base
  belongs_to :blog
  belongs_to :tag
end

How do I select all the Blogs with a given tag_id ?

So far I have: TaggedBlogposts.all.where("tag_id=?", "1"), which returns:

+----+---------+--------+-------------------------+-------------------------+
| id | blog_id | tag_id | created_at              | updated_at              |
+----+---------+--------+-------------------------+-------------------------+
| 2  | 1       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 4  | 2       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 7  | 3       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 15 | 6       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 17 | 7       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 24 | 9       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 33 | 13      | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 36 | 15      | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 46 | 18      | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 47 | 19      | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
+----+---------+--------+-------------------------+-------------------------+

But from this join table, I want to return the corresponding blog objects. Something like:

Blog.all.where(tag_id:1, through: TaggedBlogposts)

Aucun commentaire:

Enregistrer un commentaire