使用用户下面的系统可以采用以下格式收藏样式:
=> #<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">
我已构建系统以启用用户以收藏用户,但由于某种原因,行Favorite.create!(:user => user)
未创建预期的收藏模型对象在用户上调用时,如上所述,在样式上调用时。相反,我得到如下nils:
=> #<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
模型定义包括favable module(见下文):
class User < ActiveRecord::Base
include Favoritable
class Style < ActiveRecord::Base
include 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
答案 0 :(得分:1)
您需要在add_favorite
中传递:favable model:
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