多态收藏模型设置中的质量分配错误

时间:2012-10-15 20:45:09

标签: ruby-on-rails-3 activerecord rspec polymorphic-associations mass-assignment

我正在尝试向我的应用添加偏好,以便用户可以选择喜欢的项目。

我尝试使用我在此处找到的代码: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 个答案:

答案 0 :(得分: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