【问题标题】:Rails 3 - Splat attr_accessible with Active RecordRails 3 - Splat attr_accessible 与 Active Record
【发布时间】:2018-01-14 06:21:00
【问题描述】:

我正在通过将 typedoptions 移动到新模型来使它们动态化,正如您在使用常量使列 t_a, t_b, t_c 可通过 *TYPED_DATA 访问之前看到的那样,但现在模型已经迁移了,我不能再做了。有什么我想念的吗?

顺便说一句,当我用 FactoryGirl 重新运行我的规范时,这会失败。

class Rules < ActiveRecord::Base
  #TYPED_DATA = %w{a b c}.map { |t| t.prepend('t_').to_sym }

  attr_accessible :name, *Typed.prefixed
end

# typed.rb
class Typed < ActiveRecord::Base
  def self.prefixed
    Typed.pluck(:name).map { |name| name.prepend('t_').to_sym }
  end
end

动态公开这些属性的最佳选择是什么?

【问题讨论】:

  • 您在测试中遇到什么错误?
  • 批量分配无法访问 t_a。

标签: ruby-on-rails ruby-on-rails-3 splat


【解决方案1】:

虽然此解决方案无法解决将 AR 查询与 splat 一起使用的技术问题。 它解决了使那些动态字段可访问的主要问题,特别是在大多数字段需要可访问的情况下,最好依赖于您要保护的那些。

class Rules < ActiveRecord::Base
  attr_protected :id, :created_at, :updated_at
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多