我正在使用bit.ly api,并试图设置控制器的create动作,以便我只能使用api一次,然后将缩短的链接存储在其中,@micropost.link
并以这种方式在我的视图中引用它。
microposts_conroller.rb
def create
@micropost = current_user.microposts.build(micropost_params)
client = Bitly.client
url = client.shorten("https://www.myapp.com/microposts/#{@micropost.id}")
@micropost.link = url.short_url
respond_to do |format|
if @micropost.save
format.html {redirect_to root_url}
format.js
else
@feed_items = []
@microposts = []
render 'static_pages/home'
end
end
end
是否可以在create动作中引用新创建的微博的id属性?
#{@micropost.id}
没有工作,我尝试了其他一些方法,但是没有任何运气。我应该以不同的方式来对待吗?
您使用.build
只能构建模型,但不保存模型。
保存模型将设置ID。因此,只有在保存模型后才能构建url。
如果保存后未设置ID,则会出现验证错误。
因此您的代码可能看起来像这样:
def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
url = Bitly.client.shorten(micropost_url(@micropost))
@micropost.update_attributes link: url.short_url
respond_to do |format|
format.html {redirect_to root_url}
format.js
end
else
@feed_items = []
@microposts = []
render 'static_pages/home'
end
end
我使用update_attributes
它将更新数据库中的参数,这更干净,然后设置链接并节省了第二次时间。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句