使用以下系统,用户可以以以下格式收藏样式:
=> #<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">
我已经构建了系统以使用户也可以收藏用户,但是由于某种原因,当在UserFavorite.create!(:user => user)
上调用时,该行没有创建预期的收藏模型对象,就像在Style上调用时一样。相反,我得到如下零点:
=> #<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
模型定义,包括最喜欢的模块(见下文):
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