我正在尝试填充活动模型的parameters
属性(来自public_activity gem),但没有成功。
class Project < ActiveRecord::Base
include PublicActivity::Model
tracked owner: ->(controller, model) { controller && controller.current_user },
parameters: ->(controller, model){
{foo: 'bar'}
}
end
第一个问题是当我更新项目时,参数哈希总是为空。第二个问题是,->(controller, model)
接收控制器和模型类,但不接收实例。我的目标是将更新集中的两个字段更新为参数(id和字符串)。
我怎样才能做到这一点?
答案 0 :(得分:8)
有点迟到但仍然可能对其他人有帮助,他们试图在PublicActivity中使用默认参数哈希。根据官方文档:
class Article < ActiveRecord::Base
include PublicActivity::Model
tracked :params => {
:title => :title,
:author_name => "Michael",
:category_name => proc {|controller, model_instance| model_instance.category.name},
:summary => proc {|controller, model_instance| truncate(model.text, :length => 30)}
}
end
你可以参考: http://rubydoc.info/gems/public_activity/PublicActivity/Tracked/ClassMethods 了解更多详情
答案 1 :(得分:1)
解决了它,虽然没有通过模型。在更复杂的情况下,您似乎不会以这种方式创建它。您可以通过回调在模型中创建它(由于缺少current_user
可能会很复杂,除非你做了一些hackery),或者在控制器中。
我这样做的方式:
<强>模型强>
class Project < ActiveRecord::Base
include PublicActivity::Common
attr_accessor :previous_status_id
before_save :remember_previous_status_id
private
def remember_prefious_status_id
self.previous_status_id = self.changes['status_id'].first if self.changes.include? 'status_id'
end
end
<强>控制器强>
# [...]
if @project.update_attributes project_params
@project.create_activity :update,
owner: current_user,
previous_status_id: @project.previous_status_id,
parameters: {
# ...
}
# ...
迁移
create_table :activities do |t|
# ...
t.belongs_to :previous_status
# ...
<强>初始化程序强>
PublicActivity::Activity.class_eval do
belongs_to :previous_status, class_name: 'Status'
end
答案 2 :(得分:0)
您可以在模型实例上设置activity_params
变量,然后将其保存到活动中。在你的情况下像这样:
class Project < ActiveRecord::Base
include PublicActivity::Model
tracked owner: ->(controller, model) { controller && controller.current_user }
end
project = Project.new
project.activity_params = {foo: 'bar'}
有关详细信息,请参阅:http://rubydoc.info/gems/public_activity/PublicActivity/Common#activity_params-instance_method
答案 3 :(得分:0)
class Project < ActiveRecord::Base
include PublicActivity::Model
tracked owner: ->(controller, model) { controller && controller.current_user
}, parameters: :previous_changes
end
以下解决方案对我有用。您可以查看以下链接,了解有关版本5 https://www.ombulabs.com/blog/rails/upgrades/active-record-5-1-api-changes.html
的活动记录api中的更改的更多更改