Rails 3:在 has_many 关联上调用数据库
您好,我有一个多对多关联,其中“帖子”有很多“感觉”,我想弄清楚如何找到用户具有特定感觉的所有帖子。我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
includes
参数应该是:feelings
- 注意复数,这就是您的关联的名称。所以应该是:
The
includes
argument should be:feelings
- notice the plural, which is what your association is named.So it should be: