Rails CRUD参数问题

Jos*_*man 0 parameters routes ruby-on-rails crud models

所以我的背景是Java Web服务,但我正试图转向ROR.

我正在使用FlexImage处理图像上传和缩略图生成.我按照指南,CRUD行为一度正常.但是,在某些时候,我的某个模型(图像)的CRUD行为被打破了.

我得到的错误代码如下:ActiveRecord::RecordNotFound in ImagesController#show -- Couldn't find Image with ID=#<Image:0x4e2bd74>.换句话说,当我告诉Rails创建/更新/销毁时,它会使对象与id混淆.这似乎表明可能存在路由问题.我认为为图像添加部分可能是麻烦,但回滚更改并没有解决它.

以下是Images模型的控制器的新,显示和更新方法:

      # images_controller.rb

        # ...

      def new
        @image = Image.new

        respond_to do |format|
          format.html # new.html.erb
          format.xml  { render :xml => @image }
        end
      end

    # ...
  def show
    @image = Image.find(params[:id])

    respond_to do |format|
      format.jpg  # show.jpg.erb 
      format.html # show.html.erb
      format.xml  { render :xml => @image }
    end
  end



    # ...

      def create
        @image = Image.new(params[:image])

        if @image.save 
        redirect_to image_url(@image)
        else
        flash[:notice] = 'Your image did not pass validation.'
        render :action => 'new'
        end
      end 
     # ...
Run Code Online (Sandbox Code Playgroud)

请注意,show()当然需要适当的id.这是用于上传新图片的new.html.erb:

# new.html.erb [upload image]
<h1>New image</h1>

<% form_for @image, :html => { :multipart => true } do |f| %>
  <%= f.error_messages %>
  <table><tr><td width="50%">
  <p>
    <%= f.label :filename %><br />
    <%= f.text_field :filename %></p>
  </td>
  <td><p><b>Upload Image</b><br />
    <%= f.file_field :image_file %><br />
    or URL: <%= f.text_field :image_file_url %>
    <%= f.hidden_field :image_file_temp %>
  </td>
  <td>
    <b>Uploaded Image:</b><br />
    <%= embedded_image_tag(@image.operate { |img| img.resize 100 }) if @image.has_image? %>
  </td>
  </tr>

  </table>
  <p>
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

<%= link_to 'Back', images_path %>
Run Code Online (Sandbox Code Playgroud)

routes.rb的相关部分如下:

# routes.rb [excerpt]

  map.resources :images
  map.image 'images/:action/:id.:format', :controller => 'images'
Run Code Online (Sandbox Code Playgroud)

另请注意,实际上会上传新图像,并且在重定向显示时抛出错误(期望在params [:id]中使用有效ID,而不是由于任何原因而被传递的对象.)

感谢您提前的帮助,如果有任何事情发生,请告诉我.

mol*_*olf 5

通过查看代码,我认为问题可能是由于image_url(@image)与非RESTful image路由结合使用而引起的.

您可能希望删除该行

map.image 'images/:action/:id.:format', :controller => 'images'
Run Code Online (Sandbox Code Playgroud)

从你的routes.rb.

这条线

map.resources :images
Run Code Online (Sandbox Code Playgroud)

应该足以暴露你的所有CRUD行动ImagesController.