开发者

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


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

That should work.


@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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜