这是模型。
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
':source
参数它应该寻找一个命名空间模型?我也尝试:recipes_recipe
过:source
参数,表名:favorites
只是“收藏夹”。