Ошибка массового присваивания в настройке полиморфной любимой модели
Я пытаюсь добавить избранное в мое приложение, чтобы пользователи могли выбирать любимые проекты.
Я попытался использовать код, который я нашел здесь: 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
на любимой модели?
Надеюсь, кто-то может помочь!
1 ответ
Решение
Решил это!
Вот файлы, которые должны были быть изменены из показанных в вопросе:
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