以下是模型。
Recipes::Recipe
:
module Recipes
class Recipe < ActiveRecord::Base
include ApplicationHelper
attr_accessible :body, :title, :author, :photos, :tags
has_many :photos
has_many :favorites
has_many :taggings
has_many :tags, :through => :taggings
belongs_to :author,
:class_name => :User,
:foreign_key => :author_id
has_many :favorers,
:source => :user,
:through => :favorites
before_create :default_values
before_validation :create_slug
validates_presence_of :title, :body, :author
validates_uniqueness_of :title, :slug
end
end
User
:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :login, :email, :password, :password_confirmation, :remember_me
has_many :recipes,
:class_name => 'Recipes::Recipe',
:foreign_key => :author_id
has_many :favorite_recipes,
:class_name => 'Recipes::Recipe',
:foreign_key => :recipe_id,
:source => :recipe,
:through => :favorites
end
end
Recipes::Favorite
:
module Recipes
class Favorite < ActiveRecord::Base
attr_accessible :user_id, :recipe_id
belongs_to :recipe,
:class_name => "Recipes::Recipe"
belongs_to :user,
:class_name => "User"
end
end
当引用Recipes::Recipe
模型上的属性时,关联起作用。如果我recipe = Recipes::Recipe.first; recipe.favorers
它可行。当我user = User.first; user.favorite_recipes
时收到错误。
错误:
1.9.3-p392 :002 > u.favorite_recipes
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association
:favorites in model User
我认为它正在尝试找到模型Favorite
,但实际上它应该是Recipes::Favorite
。我在Rails文档中读到:foreign_key
和:class_name
在has_many :through
关联中被忽略,但我仍尝试过它们,但它仍然无效。所以现在我想知道,我怎么能告诉has_many :through
的{{1}}参数它应该寻找命名空间模型?我还为:source
参数尝试了:recipes_recipe
,而:source
的表名只是“收藏夹”。
答案 0 :(得分:2)
我发现了问题。
解决方案出错了。
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association
:favorites in model User
has_many :through
关联正在has_many :favorites
型号上寻找User
。
所以,我刚刚添加了has_many :favorites, :class_name => 'Recipes::Favorite'
,上面的代码开始为两个协会工作。