【发布时间】:2014-04-20 10:19:15
【问题描述】:
我正在制作一个 Rails 应用程序,用户可以在其中将 soundcloud 链接粘贴到输入字段中。然后,此链接被发送到我的post_controller 中的创建操作,并用于获取该歌曲的 JSON 文件。
# 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,但问题是它似乎是在创建操作中的所有代码之后完成的。我希望在创建操作中的所有代码之前完成验证。 (因为如果没有有效的链接,创建操作中的代码将不起作用)。
我该怎么做或有更好的做法?
【问题讨论】:
-
检查这个网址 :) [coverhound.com/blog/post/…
标签: ruby-on-rails validation ruby-on-rails-4 actioncontroller