2017-04-17 3 views
1

youtube URL을 추가 할 수있는 activeadmin 양식이 있습니다. 동영상 모델에서이 URL의 유효성을 검사합니다. 새 비디오를 추가하려고 할 때 제대로 작동하지만 비디오를 편집 할 때는 아무 것도하지 않습니다.
응용 프로그램/관리/video.rb :Ruby on Rails - Activeadmin - 가상 속성이있는 모델 업데이트

ActiveAdmin.register Media, as: 'Videos' do  
form do |f| 
     f.inputs "Add youtube video" do 
      f.input :category 
      f.semantic_errors :error 
      f.has_many :videos, allow_destroy: true do |g| 
       g.input :mylink, :label => "Youtube link : ", :type => :text 
     end 
     actions 
     end 
    end 
end 

모델/video.rb :

before_update 방법은 트리거되지 않습니다처럼 보이는
class Video < ApplicationRecord 
    belongs_to :media 
    attr_accessor :mylink 
    YT_LINK_FORMAT = /\A.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*\z/i 
    before_create :before_add_to_galerie 
    before_update :before_add_to_galerie 

    def before_add_to_galerie 
    uid = @mylink.match(YT_LINK_FORMAT) 
    self.uid = uid[2] if uid && uid[2] 
    if self.uid.to_s.length != 11 
     self.errors.add(:mylink, 'is invalid.') 
     throw :abort 
     false 
    elsif Video.where(uid: self.uid).any? 
     self.errors.add(:mylink, 'is not unique.') 
     throw :abort 
     false 
    end 
end 

validates :mylink, presence: true, format: YT_LINK_FORMAT 
end 

.
어떻게 편집 작업을 할 수 있습니까?

편집 : 나는 그것이 미디어 모델에 대한 before_update 링크를 호출하고 비디오 one.But에 대한 아니라고 알았습니다. 괜찮습니다.

+0

를 사용할 수 있는지? 기존 레코드를 업데이트하려고 시도 했습니까? – Bohdan

+0

방금 ​​전에 콘솔에 텍스트를 인쇄하고 아무 것도 인쇄하지 않는 before_update에서 다른 메서드를 호출하려고 시도했습니다 – KingOfBabu

+0

가상 특성을 사용하지 않을 때 작동하지만 실제로이 링크의 유효성을 검사해야합니다 – KingOfBabu

답변

1

나 문제 바꿔 해보자 : 당신은 모델 Video

  • Video

    1. 것은 my_link
    2. Videobefore_update 콜백에게 before_add_to_galerie
    3. 을 가진 가상 속성을 당신은 트리거이 콜백을 원하는있다 my_link 만 변경된 경우

    이 모양이 맞습니까? 그래서 먼저,이 옵션이있는 경우 - 당신이 my_link

    class Video < ApplicationRecord 
        attr_reader :my_link 
        # ... 
        def my_link=(val) 
        return val if val == my_link 
        @my_link = val 
        self.updated_at = Time.zone.now 
        end 
    end 
    

    와 함께 updated_at 변경을하거나 당신이 왜 당신이 그것을 트리거 아니에요 생각 ActiveModel