trying_hal9000
trying_hal9000

Reputation: 4403

Rails 3: database calls for has_many :through relationship

I have an array of posts called @posts. Post model has_many :feelings :through => :feelingships.

How do I take the array of posts and narrow them it down to only the posts with a specific feeling?

I tried the code below but it doesn't work :(

@specific_feeling_posts = @posts.feeling.where(:feeling => "happy") 

Models

class Post < ActiveRecord::Base
  has_many :feelingships
  has_many :feelings, :through => :feelingships
  belongs_to :user
end

class Feeling < ActiveRecord::Base
  has_many :feelingships
  has_many :posts, :through => :feelingships
end

class Feelingship < ActiveRecord::Base
  belongs_to :post
  belongs_to :feeling
end

Upvotes: 0

Views: 199

Answers (2)

Kaushik Thirthappa
Kaushik Thirthappa

Reputation: 1051

@specific_feelings_post=Post.join(:feelings).where("feelings.title= ?","specific_feeling")

Its the same line as bricker has written above. The question mark is to avoid SQL injection. In short, the security of the database is handled by the ActiveRecord in Rails. By doing this, you will create properly escaped SQl and is immune from SQL injection.

Upvotes: 0

bricker
bricker

Reputation: 8941

@happy_posts = Post.joins(:feelings).where("feelings.title = ?", "happy")

That should work.

Upvotes: 1

Related Questions