0

这是模型。

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只是“收藏夹”。

4

1 回答 1

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',上面的代码开始为这两个关联工作。

于 2013-07-06T07:22:51.797 回答