0

我需要添加

attr_accessible :user

对engagecsm gem 的投票模型。

请参阅此问题了解我为什么需要这样做(跳至答案):Rails Engage!错误(无法批量分配受保护的属性:用户)

现在,通常我会在 github 上分叉并添加行,但没有 github,而且我认为将其公开或其他内容可能违反规则。无论如何,所以我刚刚在 gemfile 中添加了 gem,如下所示:https ://rubygems.org/gems/engagecsm

通过在本地计算机上打开 gem 并输入该行,我已将该行添加到本地安装的engagecsm 中。但是,我希望这适用于 Heroku。

4

2 回答 2

1

在您的lib文件夹中,创建一个文件(我的建议是lib/ext/engagecms/vote.rb),然后输入以下内容:

require 'engagecms' #make this the correct require for the gem, the goal is to force the gem to load before your code

class Vote < ActiveRecord::Base # you'll need to make this declaration equal the engage one
  attr_accessible :user
end

这是猴子修补代码,因此将来可能会由于升级而中断。

更好的长期策略是创建一个包装器,将Vote.create(params[:vote])params[:vote]具有您的user属性)转换为

user = params[:vote].delete(:user)

Vote.create(params[:vote]) do |v|
  v.user = user
end

这种技术可以让你表现得好像它是可访问的,但避免了猴子补丁,由于存在损坏和冲突的风险,这不是最佳实践。

于 2013-02-03T23:15:41.677 回答
1

config/application.rb

# run before each request in dev, or during initialization in test & prod
config.to_prepare do
  # re-open the `Vote` class so we can make some changes
  Vote.class_exec do
    # the custom changes
    attr_accessible :user
  end
end
于 2013-02-03T23:16:35.237 回答