【问题标题】:Rails 3: calling database on a has_many associationRails 3:在 has_many 关联上调用数据库
【发布时间】:2011-12-13 18:46:55
【问题描述】:

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

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: 找不到名为‘feeling’的关联;也许你拼错了?”

 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

【问题讨论】:

  • 你在 @user 上调用的“feed”是什么?它可能应该是“帖子”

标签: ruby-on-rails database ruby-on-rails-3 rails-activerecord


【解决方案1】:

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

应该是这样的:

@user.posts.includes(:feelings)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多