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:foreign_keyRails のドキュメントを読んで、関連付け: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 に答える