2013-06-01 3 views
0

заносить в избранное Я стараюсь следовать этому сообщению, добавив избранное мое приложение Rails: Implement "Add to favorites" in Rails 3 & 4Рельсы Ассоциация Модель:

В моем приложении, я хотел бы, чтобы пользователи могли любимые проекты. Сейчас, когда я пытаюсь реализовать link_to действия избранных в контроллере проекта, я получаю сообщение об ошибке:

ActiveRecord::HasManyThroughSourceAssociationNotFoundError in ProjectsController#favorite 
Could not find the source association(s) :favorite or :favorites in model FavoriteProject. 
Try 'has_many :favorites, :through => :favorite_projects, :source => <name>'. Is it one of :project or :user? 

Как я могу исправить эту ошибку?

favorite_project.rb:

class FavoriteProject < ActiveRecord::Base 
    attr_accessible :project_id, :user_id 
    belongs_to :project 
    belongs_to :user 
end 

user.rb:

class User < ActiveRecord::Base 
    extend FriendlyId 
    friendly_id :username 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :confirmable, 
    # :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable, 
     :token_authenticatable, :confirmable, :lockable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :avatar 
    # attr_accessible :title, :body 

    has_many :projects, :dependent => :destroy 

    # Favorite projects 
    has_many :favorite_projects # just the 'relationships' 
    has_many :favorites, :through => :favorite_projects # projects a user favorites 

    accepts_nested_attributes_for :projects 

    mount_uploader :avatar, AvatarUploader 

    validates :username, :presence => true 
    validates :email, :presence => true 
end 

project.rb:

class Project < ActiveRecord::Base 
    attr_accessible :title, :images_attributes, :ancestry, :user_id 
    has_many :steps, :dependent => :destroy 
    has_many :images, :dependent => :destroy 

    belongs_to :user 

    # Favorited by users 
    has_many :favorite_projects 
    has_many :favorited_by, :through => :favorite_projects, :source => :user # users that favorite a project 

    accepts_nested_attributes_for :steps 
    accepts_nested_attributes_for :images 

    validates :title, :presence => true 
end 

projects_controller.rb

def favorite 
    current_user.favorites << @project 
    redirect_to :back 
    end 

routes.rb

Build::Application.routes.draw do 

    devise_for :users, :controllers => {:registrations => :registrations} 
    get "home/index" 

    resources :users do 
    match 'users/:id' => 'users#username' 
    end 

    resources :projects do 
    collection {post :sort} 
    get :editTitle, on: :collection 
    put :favorite, on: :member 
    resources :steps do 
     collection {post :sort} 
     get :create_branch_a, on: :collection 
     get :create_branch_b, on: :collection 
     get :update_ancestry, on: :collection 
     get :edit_redirect, on: :collection 
     get :show_redirect, on: :collection 
     end 
     match "steps/:id" => "steps#number", :as => :number 
    end 

    resources :images do 
    collection {post :sort} 
    end 

    root :to => 'home#index' 

    post "versions/:id/revert" => "versions#revert", :as => "revert_version" 

end 

index.html.erb файл вид:

<%= link_to "", favorite_project_path(@project), method: :put, :class=> "icon-star-empty favoriteStar", :title=> "Favorite", :rel=>"tooltip" %> 
+0

Вы пытались сохранить current_user после добавления '@ project'? –

+0

Я не уверен, зачем мне это нужно. Можете ли вы объяснить дальше? – scientiffic

+1

Попробуйте это в консоли и посмотрите, какой результат вы получите. Я не уверен, что сохранение - правильный ответ здесь, зависит от того, как вы создаете '@ project' в контроллере. Кроме того, проверьте, что сказал @Babur ниже. –

ответ

1

Вы

has_many :favorites, :through => :favorite_projects 

Но нет favorites ассоциации в FavoriteProject модели. Только belongs_to :project. Это должно быть:

has_many :favorites, :through => :favorite_projects, :source => :project 
+0

спасибо! У меня также была дополнительная ошибка в том, что «@project» не был определен в моем контроллере. Я добавил следующую строку в мое любимое действие: @project = Project.find (params [: id]) – scientiffic

Смежные вопросы