Rails 3:在 has_many 关联上调用数据库

发布于 2024-12-11 06:35:54 字数 1087 浏览 3 评论 0原文

您好,我有一个多对多关联,其中“帖子”有很多“感觉”,我想弄清楚如何找到用户具有特定感觉的所有帖子。我的 Feeling 模型有一个“名称”属性。

class User < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

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
  attr_accessible :post_id, :feeling_id
end

我尝试了这个,但它说我有错误的关联:“ActiveRecord::ConfigurationError: 未找到名为“感觉”的关联;也许您拼写错误?”

 def feeling
  @user = User.find(params[:id])
  @feed_items= @user.posts.includes(:feeling).where(
          ['`feelings`.name = ?', params[:feeling]])
  @feed_items = @feed_items.paginate(:per_page => "10", :page => params[:page])
render 'shared/_feed', :layout => 'head_layout'
end

Hi I have a many to many association where 'posts' have many 'feeling', I'd like to figure out how to find all the posts with a specific feeling by the user. My Feeling model has a 'name' attribute.

class User < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

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
  attr_accessible :post_id, :feeling_id
end

I tried this but it says I have the wrong association: "ActiveRecord::ConfigurationError: Association named 'feeling' was not found; perhaps you misspelled it?"

 def feeling
  @user = User.find(params[:id])
  @feed_items= @user.posts.includes(:feeling).where(
          ['`feelings`.name = ?', params[:feeling]])
  @feed_items = @feed_items.paginate(:per_page => "10", :page => params[:page])
render 'shared/_feed', :layout => 'head_layout'
end

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

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

发布评论

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

评论(1

静水深流 2024-12-18 06:35:54

includes 参数应该是 :feelings - 注意复数,这就是您的关联的名称。

所以应该是:

@user.posts.includes(:feelings)

The includes argument should be :feelings - notice the plural, which is what your association is named.

So it should be:

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