我正在製作一個rails應用程序,用戶可以在輸入字段中粘貼一個soundcloud鏈接。然後,將此鏈接發送到我的post_controller
中的創建操作,並用於獲取該歌曲的JSON文件。Rails:在控制器中處理它們之前驗證參數?
# 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
在Post
模型中,我試圖運行validates :link, presence: true
,但問題是,它似乎在以後創建操作所有的代碼來完成。我希望在創建操作中的所有代碼之前完成驗證。 (因爲如果沒有有效的鏈接,創建操作中的代碼將不起作用)。
我該怎麼做,或者有更好的做法?
檢查這個網址:) [http://coverhound.com/blog/post/better-conditional-validations-in-rails] –