【问题标题】:Rails: Is there an efficient way to get all whitelisted attributes with values?Rails:有没有一种有效的方法来获取所有列入白名单的属性的值?
【发布时间】:2013-01-28 17:03:04
【问题描述】:

我正在尝试使用模型作为模板来创建新模型。但是,我只想使用模板模型中的attr_accessible 属性。

这就是我现在正在做的事情。它有效,但似乎太复杂了。

def copy_attrs_and_errors(other)
  self.class.attr_accessible[:default].to_a.each do |attr|
    eval("self.#{attr} = other.#{attr}") unless attr.blank?
  end
end

我想说一些简单的话:

self.attributes = other.whitelist_attributes(:default)

谢谢。

【问题讨论】:

  • 请注意:.accessible_attributes.attr_accessible[:default] 的同义词,我觉得它更具可读性。
  • 好点。这似乎将角色作为参数并默认使用:default。谢谢。

标签: ruby-on-rails-3 activerecord mass-assignment


【解决方案1】:

这有点疯狂,但你可以在模块或其他任何东西中做这样的事情:

def self.from_accessible_attributes(other)
  values     = other.attributes.values_at(*other.class.accessible_attributes)
  attributes = Hash[other.class.accessible_attributes.zip(values)]
  new(attributes)
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 2011-06-19
    • 1970-01-01
    • 2012-06-13
    • 2021-12-17
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多