【问题标题】:Is there a better way to create read-only attributes in rails?有没有更好的方法在 Rails 中创建只读属性?
【发布时间】:2013-12-08 03:07:03
【问题描述】:

我正在 Rails 中创建一个 ActiveRecord 对象,我希望它具有只读属性。我最初尝试使用attr_readonly,但很沮丧地发现它:

  1. Disabled mass-updating of those properties, even on new records
  2. 如果记录已保存,则未引发异常,或通知您只读属性正在以任何方式更改。

我想要这两个功能;这是我的实现尝试:

# For use with ActiveRecord

module ReadOnlyAttributes

  class ReadOnlyAttributeException < StandardError
  end

  def create_or_update # Private, but its what every method gets funneled through.
    if !self.new_record? && self.respond_to?(:read_only_attributes)
      changed_symbols = self.changed.map(&:to_sym)
      if changed_symbols.intersect?(self.read_only_attributes)
        raise ReadOnlyAttributeException, "Readonly attributes modified on #{self.class}: #{changed_symbols & self.read_only_attributes}"
      end
    end

    super
  end

end

然后在我的模型中:

class Model < ActiveRecord::Base

  include ReadOnlyAttributes

  def read_only_attributes
    [:event_type]
  end

end

是否有内置或更好的方法来获取满足上述要求的只读属性?

我对 Ruby/Rails 还是很陌生,所以我也很欣赏任何风格的 cmets。

【问题讨论】:

    标签: ruby-on-rails ruby module


    【解决方案1】:

    你试过了吗:

    class Model < ActiveRecord::Base    
      before_save :protect_attributes
    
      private
      def protect_attributes
         false if !new_record? && event_type_changed?
      end
    end
    

    另一个想法是,为什么要在模型级别执行此操作?只读属性和只能在控制器的创建操作中写入的属性有什么区别?你总是可以这样做:

    class EventController < ActionController::Base
      def create
        @event = Event.new params.require(:event).permit :event_name, :event_type
      end
    
      def update
        @event = Event.find(params[:id]).update params.require(:event).permit(:event_name)
      end
    end
    

    【讨论】:

    • 效果很好,谢谢!此特定对象用于内部记录保存,并且没有面向公众的控制器。
    • 很高兴我能帮上忙。另一种稍微好一点的方法是使用自定义验证器。
    • 最好不要在控制器中强制执行,因为您可能会使用另一种方式对模型进行 CRUD,例如rake 任务或控制台。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 2012-11-26
    相关资源
    最近更新 更多