I am trying to adding favouriting to my app so that users can select favourite projects.
I have tried to use the code that I found here: http://snippets.aktagon.com/snippets/588-How-to-implement-favorites-in-Rails-with-polymorphic-associations
Here's my current situation:
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
When I run the test though, the user_id test passes but I get the following for it { should be_valid }
:
Failure/Error: user.favourite_projects.build(favourable: project.id)
ActiveModel::MassAssignmentSecurity::Error:
Can't mass-assign protected attributes: favourable
Am I doing something wrong in my test?
Or the way I am calling .build
?
Or in the attr_accessible
on the Favourite model?
Hope someone can help!