사용자가 입력란에 사운드 클라우드 링크를 붙여 넣을 수있는 레일 앱을 만들고 있습니다. 그런 다음이 링크는 내 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
을 실행하기 위해 노력하고있어,하지만 문제는 활동 만들기의 모든 코드 뒤에 할 것으로 보인다는 것이다. 작성 작업의 모든 코드보다 먼저 유효성 검사를 수행해야합니다. (유효한 링크가 없으므로 만들기 작업의 코드가 작동하지 않습니다.
어떻게해야합니까? 아니면 더 나은 방법이 있습니까?
확인이 URL : [http://coverhound.com/blog/post/better-conditional-validations-in-rails] –