我正在尝试将收藏添加到我的应用程序中,以便用户可以选择最喜欢的项目。
我尝试使用在这里找到的代码:http: //snippets.aktagon.com/snippets/588-How-to-implement-favorites-in-Rails-with-polymorphic-associations
这是我目前的情况:
用户.rb
class User < ActiveRecord::Base
has_many :projects
has_many :favourites
has_many :favourite_projects, :through => :favourites, :source => :favourable, :source_type => "Project"
end
项目.rb
class Project < ActiveRecord::Base
belongs_to :user
has_many :tasks
accepts_nested_attributes_for :tasks
has_many :favourites, :as => :favourable
has_many :fans, :through => :favourites, :source => :user
end
任务.rb
class Task < ActiveRecord::Base
belongs_to :project
end
最喜欢的.rb
class Favourite < ActiveRecord::Base
belongs_to :user
belongs_to :favourable, :polymorphic => true
attr_accessible :user, :favourable
end
favourite_spec.rb
require 'spec_helper'
describe Favourite do
let(:user) { FactoryGirl.create(:user) }
let(:project) { FactoryGirl.create(:project_with_task) }
let(:favourite_project) do
user.favourite_projects.build(favourable: project.id)
end
subject { favourite_project }
it { should be_valid }
describe "accessible attributes" do
it "should not allow access to user_id" do
expect do
Favourite.new(user_id: user.id)
end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
end
end
end
但是,当我运行测试时, user_id 测试通过了,但我得到以下信息it { should be_valid }
:
Failure/Error: user.favourite_projects.build(favourable: project.id)
ActiveModel::MassAssignmentSecurity::Error:
Can't mass-assign protected attributes: favourable
我在测试中做错了吗?
还是我打电话的方式.build
?
还是在attr_accessible
最喜欢的型号上?
希望有人能帮忙!