2012-02-06 47 views
0

我正在上傳圖像,並希望將其與當前項目相關聯。我位於URL example.com/projects/1的項目中並呈現此內容形式:Rails 3.1:將project_id與新上傳的圖像相關聯

<%= semantic_form_for @image, :html => { :multipart => true } do |f|%> 
    <%= f.semantic_errors %> 
    <%= f.inputs do %> 
    <%= f.input :title %> 
    <%= f.input :description %> 
    <%= f.input :image, :as => :file %> 
    <% end %> 
    <%= f.buttons do %> 
    <%= f.commit_button :label => 'Upload Image', :button_html => { :class => "btn primary" } %> 
    <% end %> 
<% end %> 

我在image.rb模型,belongs_to :project和project.rb模型設定,has_many :images

我images_controller.rb創建方法是這樣的:

def create 
    image = params[:image] 
    if user_signed_in? 
    @image = Image.new(:title => image[:title], 
         :description => image[:description], 
         :user_id => current_user.id, 
         :project_id => params[:id]) 
    if @image.save 
    flash[:success] = "Successfully uploaded an image" 
    redirect_to project_path(params[:id]) and return 
    else 
    flash[:error] = "Error with image upload" 
    redirect_to new_image_path and return 
    end 
else 
    redirect_to root_path 
end  
end 

圖像已創建,但未能將圖像與project_id關聯。我知道問題是params[:id]沒有拉入project_id,我該如何從網址中提取項目ID並將其與圖片關聯?

回答

1

您應該使用您的關聯來創建新的圖像。

@image = Project.find(params[:id]).images.create(:title => image[:title], 
        :description => image[:description], 
        :user => current_user) 
if @image.save... 

如果這不起作用,請張貼您的routes.rb的內容和從發佈請求中選中的url。

+0

感謝您的幫助。這不起作用,我得到了錯誤「找不到沒有ID的項目」。 POST網址:開始POST「/ images」。在routes.rb我有兩個資源:圖像和資源:項目 – ramz15 2012-02-06 22:25:02

+0

這就是爲什麼你得到這個錯誤,URL是錯誤的,不包含ID參數。您需要傳遞它,隱藏字段是一種相對簡單的方法,另一種方法是使用嵌套資源。 http://guides.rubyonrails.org/routing.html#nested-resources – Gazler 2012-02-06 22:28:29

+0

謝謝Gazler!我用隱藏字段解決了這個問題,對於n00b問題感到抱歉:) – ramz15 2012-02-06 23:32:50