2014-05-09 36 views
1

我使用bit.ly api,並試圖設置我的控制器的創建操作,以便我可以只使用api一次,然後將縮短的鏈接存儲在@micropost.link中,並在我的視圖中引用它。是否可以在控制器的創建操作中引用id屬性?

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 

是否有可能創建操作中引用新創建的微柱id屬性?
#{@micropost.id}不能正常工作,我嘗試了其他一些東西,但沒有任何運氣。我應該以不同的方式處理這個問題嗎

回答

2

試試您使用.build只建立了一個模型,但不保存它。

保存模型將設置ID。所以你只能在保存模型後建立網址。

如果保存後未設置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將在數據庫中更新,這是清潔,然後設置鏈接,並節省了第二次的參數。

+0

我不知道如何定義'update_params'方法,但是我可以用'update_attributes'來代替它,它工作。 '@micropost.update_attributes:link => url.short_url'謝謝 – heartmo

+0

你說得對,那就是我想寫的東西:) :) – nathanvda

3

假設您使用SQL數據庫引擎,@micropost將不會有一個ID,直到您保存它。最有可能你需要保存新創建的模型實例兩次,一次獲得一個id,然後第二次分配「link」屬性。

+1

這很可能會發生在控制器之外的某處,比如在重試邏輯延遲的工作中。 –

1

有這個

def create 
    @micropost = current_user.microposts.build(micropost_params) 

    if @micropost.save #micropost is created 

    client = Bitly.client 
    #using the micropost id here below 
    url = client.shorten("https://www.myapp.com/microposts/#{@micropost.id}") 
    @micropost.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 
+0

您的代碼格式會傷害我的眼睛。 – nathanvda

+0

@nathanvda道歉,你可以建議我可以改進。 – Pavan

+0

@nathanvda我剛剛更新。現在看起來如何? – Pavan

相關問題