0

사용자가 입력란에 사운드 클라우드 링크를 붙여 넣을 수있는 레일 앱을 만들고 있습니다. 그런 다음이 링크는 내 post_controller에있는 생성 작업으로 보내지고 해당 노래에 대한 JSON 파일을 가져 오는 데 사용됩니다. Post 모델에서 레일 : 컨트롤러에서 처리되기 전에 매개 변수의 유효성을 검사합니까?

# app/controllers/post_controller.rb 

def create 
    require 'open-uri' 

    raw_link = params[:post][:link] 

    raw_link.downcase.include? "soundcloud.com/" 
    tmp_media_json = JSON.load(open("http://soundcloud.com/oembed?format=json&url=#{raw_link}")) 
    if tmp_media_json['thumbnail_url']["placeholder"] 
    tmp_media_json['thumbnail_url'] = JSON.load(open("http://soundcloud.com/oembed?format=json&url=#{tmp_media_json['author_url']}"))['thumbnail_url'] 
    end 

    media_thumbnail = tmp_media_json['thumbnail_url'].gsub('t500x500.jpg', 't80x80.jpg') 
    media_title = tmp_media_json['title'] 
    media_iframe = tmp_media_json['html'] 
    media_type = params[:post][:media_type] 

    @post = Post.new(link: media_iframe, title: media_title, thumbnail: media_thumbnail, media_type: media_type) 

    respond_to do |format| 
    if @post.save 
     format.js { render :file => "/pages/create_new_post.js.erb" } 
     format.html { redirect_to @post, notice: 'Post was successfully created.' } 
     format.json { render action: 'show', status: :created, location: @post } 
    else 
     format.html { render action: 'new' } 
     format.json { render json: @post.errors, status: :unprocessable_entity } 
    end 
    end 
end 

, 나는 validates :link, presence: true을 실행하기 위해 노력하고있어,하지만 문제는 활동 만들기의 모든 코드 뒤에 할 것으로 보인다는 것이다. 작성 작업의 모든 코드보다 먼저 유효성 검사를 수행해야합니다. (유효한 링크가 없으므로 만들기 작업의 코드가 작동하지 않습니다.

어떻게해야합니까? 아니면 더 나은 방법이 있습니까?

+0

확인이 URL : [http://coverhound.com/blog/post/better-conditional-validations-in-rails] –

답변

0
class YourController < ApplicationController 
    before_filter :my_filter 
    before_filter :my_filter2, :except => [:index, :new, :create] 
    def my_filter 
    # your code gose here 
    end 
    def my_filter2 
    # your code gose here 
    end 
........ 
end 
1

json 가져 오기 코드를 컨트롤러에서 모델로 이동해야합니다.

또한이 질문은 사운드 클라우드의 JSON로드 결과 인 "링크"속성의 유효성을 검사하기 때문에 약간 혼란 스럽습니다. 이런 종류의 질문은 불가능합니다. . 말했다되고 그건

는, 그래서 위의 코드가 완료되지

# controller... 
def create 
    @post = Post.new_from_link(params[:post][:link], params[:post][:media_type]) 
    @post.save 
    ...render... 

end 

# post model... 
class Post < ActiveRecord::Base 
    attr_accessor :raw_link, :raw_media_type 

    def new_from_link(raw_link, raw_media_type) 
    @raw_link = raw_link 
    @raw_media_type = raw_media_type 
    end 

    def assign_soundcloud_attributes 
    fetcher = SoundCloudFetcher.new(raw_link, raw_media_type).fetch 
    self.link = fetcher.link 
    self.media_type = fetcher.media_type 
    self.media_thumbnail = fetcher.media_thumbnail 
    self.media_iframe = fetcher.media_iframe 
    end 
end 

class SoundCloudFetcher 
    attr_accessor :link, :media_type, :media_thumbnail, :media_title, :media_iframe 

    def self.initialize(raw_link, raw_media_type) 
    @raw_link = raw_link 
    @raw_media_type = raw_media_type 
    end 

    def fetch 
    ...go get and set the data... 
    return self 
    end 
end 

린 컨트롤러를 유지한다. #assign_soundcloud_attributes에 대한 실제 호출이 없습니다. 이 디자인을 사용하면 전화를 걸고 자하는 곳을 이동할 수 있습니다. #new_from_link에 전화를 걸거나 필요에 따라 before_validation 또는 before_create 콜백에 전화를 걸 수 있습니다.

이 문제를 해결하려면 전달 된 raw_link의 유효성을 검사하거나 soundcloud API 호출에서 되돌아 오는 링크의 유효성을 검사하고 싶습니까?

원시 링크의 유효성을 검사하는 경우 호출을 #assign_soundcloud_attributes로 이동하여 before_create 콜백으로 이동하십시오.

SoundCloud API 호출에서 검색된 실제 링크 속성의 유효성을 검사하는 경우 #new_from_link 또는 #before_validation 콜백에 넣으십시오.

0

before_filter를 rails_parms 보석과 함께 사용할 수 있습니다.

그것은 다음과 같이 작동 https://github.com/nicolasblanco/rails_param

참조 :

param! :q,   String, required: true 
param! :categories, Array 
param! :sort,  String, default: "title" 
param! :order,  String, in: %w(asc desc), transform: :downcase, default: "asc" 
param! :price,  String, format: /[<\=>]\s*\$\d+/