2013-04-06 35 views
1

中的格式使用下面用戶系統能夠喜歡風格不能用喜歡的用戶態關聯

=> #<Favorite id: 59, user_id: 2, favoritable_id: 15, favoritable_type: "Style", created_at: "2013-04-06 08:47:08", updated_at: "2013-04-06 08:47:08"> 

我已經建立系統,以使用戶收藏用戶但由於某種原因,行0123¾未在用戶上調用時創建預期最喜歡的模型對象,如上調用時樣式。相反,我下面讓尼爾斯:

=> #<Favorite id: 65, user_id: 2, favoritable_id: nil, favoritable_type: nil, created_at: "2013-04-06 09:35:07", updated_at: "2013-04-06 09:35:07"> 


問題是以上。詳細信息如下



喜愛職業:

class Favorite < ActiveRecord::Base 
belongs_to :favoritable, :polymorphic => true 
belongs_to :user 
attr_accessible :user 
validates_presence_of :user 
validates_uniqueness_of :user_id, :scope => [:favoritable_type, :favoritable_id] 
end 

模型定義包括favoritable模塊(見下文):

class User < ActiveRecord::Base 
    include Favoritable 

class Style < ActiveRecord::Base 
    include Favoritable 

Favoritable模塊:

module Favoritable 
    extend ActiveSupport::Concern 

    included do 
    attr_accessible :favorites 
    has_many :favorites, :as => :favoritable, :autosave => true 
    accepts_nested_attributes_for :favorites 

    def add_favorite(user) 
     self.favorites << Favorite.create!(:user => user) 
     save 
    end 

    def delete_favorite(user) 
     self.favorites.where(:user_id => user.id).each do |favorite| 
     favorite.destroy 
     end 
    end 

    end 

end 

收藏控制器:

class FavoritesController < ApplicationController 

    def fav_user 
    @user = User.find(params[:id]) 
    @user.add_favorite(current_user) 
    respond_to do |format| 
     format.js { render :action => "update_favorite_disp", :layout => false } 
    end 
    end 

    def delete_fav_user 
    @user = User.find(params[:id]) 
    respond_to do |format| 
     if @user.delete_favorite(current_user) 
     format.js { render :action => "update_favorite_disp", :layout => false } 
     end 
    end 
    end 

    def fav_style 
    @style = Style.find(params[:id]) 
    @style.add_favorite(current_user) 
    respond_to do |format| 
     format.js { render :action => "update_favorite", :layout => false } 
    end 
    end 

    def delete_fav_style 
    @style = Style.find(params[:id]) 
    respond_to do |format| 
     if @style.delete_favorite(current_user) 
     format.js { render :action => "update_favorite", :layout => false } 
     end 
    end 
    end 

end 

回答

1

您需要在經過:favoritable模型add_favorite

def add_favorite(user) 
    Favorite.create!(:user =>user, :favoritable => self) 
save 

delete_favorite也需要基礎上刪除了:favoritable_id,而不是:user_id

def delete_favorite(user) 
    user.favorites.where(:favoritable_id => self.id).each do |favorite| 
    favorite.destroy 
    end 
end 
+0

嗚呼!工作很好。 – Abram 2013-04-06 21:49:01