0

我正在嘗試在我的應用中添加favouriting,以便用戶可以選擇最喜歡的項目。多態最愛模型設置中的質量分配錯誤

我曾嘗試使用,我發現這裏的代碼:http://snippets.aktagon.com/snippets/588-How-to-implement-favorites-in-Rails-with-polymorphic-associations

這是我目前的情況:

user.rb

class User < ActiveRecord::Base 
    has_many :projects 
    has_many :favourites 
    has_many :favourite_projects, :through => :favourites, :source => :favourable, :source_type => "Project" 
end 

project.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 

task.rb

class Task < ActiveRecord::Base 
    belongs_to :project 
end 

favourite.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的收藏模式?

希望有人能幫助!

回答

0

解決了!

下面是必須從問題中顯示的那些修改過的文件:

favourites.rb

class Favourite < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :favourable, :polymorphic => true 
    attr_accessible :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.favourites.build(favourable: project) 
    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 
    it "should not allow access to user" do 
     expect do 
     Favourite.new(user: user) 
     end.to raise_error(ActiveModel::MassAssignmentSecurity::Error) 
    end 
    end 

end