Rails 3:数据库调用 has_many :through 关系
我有一系列名为@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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那应该有效。
That should work.
它与上面写的布里克是同一行。问号是为了避免SQL注入。
简而言之,数据库的安全性是由Rails中的ActiveRecord来处理的。通过这样做,您将创建正确转义的 SQl 并且不受 SQL 注入的影响。
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.