![](/img/trans.png)
[英]has_many through: Why do I always need 2 associations for each of the 3 models?
[英]How do I use the :source parameter on has_many :through associations with models that are namespaced?
這是模型。
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
recipe = Recipes::Recipe.first; recipe.favorers
它的工作原理。 當我做user = User.first; user.favorite_recipes
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
關聯,但我還是嘗試了它們,但它仍然無效。 所以現在我想知道,我怎么能告訴一個has_many :through
:source
參數它應該找一個命名空間模型? 我也嘗試過:recipes_recipe
:source
參數,表名為:favorites
只是'收藏夾'。
我解決了這個問題。
解決方案是錯誤的。
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association
:favorites in model User
has_many :through
association正在尋找User
模型上的has_many :favorites
。
所以,我剛剛添加了has_many :favorites, :class_name => 'Recipes::Favorite'
,上面的代碼開始為兩個協會工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.