읽기 전용 속성을 갖고 싶은 Rails에서 ActiveRecord 객체를 생성하고 있습니다. 나는 처음에 사용을 시도 attr_readonly
했지만 그것을 발견하고 실망했습니다.
이 두 기능을 모두 원합니다. 이것은 구현에 대한 나의 시도입니다.
# 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를 처음 접하기 때문에 어떤 스타일 주석도 고맙게 생각합니다.
이것을 시도해 보셨습니까?
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
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다