Rails 3:数据库调用 has_many :through 关系

发布于 2024-12-09 02:50:59 字数 606 浏览 2 评论 0原文

我有一系列名为@posts 的帖子。发布模型 has_many :feelings :through => : 感情。

如何获取一系列帖子并将其范围缩小到仅具有特定感觉的帖子?

我尝试了下面的代码,但它不起作用:(

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

模型

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

十年不长 2024-12-16 02:50:59
@happy_posts = Post.joins(:feelings).where("feelings.title = ?", "happy")

那应该有效。

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

That should work.

守不住的情 2024-12-16 02:50:59
@specific_feelings_post=Post.join(:feelings).where("feelings.title= ?","specific_feeling")

它与上面写的布里克是同一行。问号是为了避免SQL注入。
简而言之,数据库的安全性是由Rails中的ActiveRecord来处理的。通过这样做,您将创建正确转义的 SQl 并且不受 SQL 注入的影响。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文