Rails 3.1:将project_id与新上传的图像相关联

时间:2012-02-06 22:08:06

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

我正在上传一张图片,想要将它与我当前的项目相关联。我在URL example.com/projects/1的一个项目中并呈现此表单:

<%= 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,如何从URL中提取项目ID并将其与图像相关联?

1 个答案:

答案 0 :(得分:1)

您应该使用关联来创建新图像。

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

如果这不起作用,请发布routes.rb的内容和从帖子请求中点击的网址。