Rails:form_for使用自定义操作设置嵌套路由

时间:2016-10-19 09:13:05

标签: ruby-on-rails ruby model-view-controller routes

我在使用自定义操作的嵌套路由时遇到问题。我想创建一个表单网址路径:... String firstArgument = args[0]; if(firstArgument.charAt(1)=='P') { int amount=Character.getNumericValue(firstArgument.charAt(2)); for (int i=0; i<amount;i++){ //Initialize valid object and maybe saving it in an list/array ... } } ... 。自定义操作的位置localhost:3000/requests/2/images/create_for_requestcreate_for_request中调用,ImagesController来自request_id。 以下是错误:

requests/show.html.erb

request.rb:

No route matches {:action=>"create_for_request", :controller=>"requests", :id=>"11"}

config.rb

class Request < ApplicationRecord
  belongs_to :user
  alias_attribute :requester, :user
  has_many :requests_has_images
  has_many :response_images, through: :requests_has_images, class_name: 'Image', source: 'image'
  has_many :chosen_images, lambda {where(chosen: true)}, through: :requests_has_images, class_name: 'Image', source: 'image'

  def is_requester(user)
    if user && self.user_id == user.id
      return true
    else
      return false
    end
  end  
end

请求/ show.html.erb:

  resources :requests do
    post 'images/create_for_request' => 'images#create_for_request'
    put 'images/edit_for_request' => 'images#edit_for_request'
    post 'images/delete_for_request' => 'images#delete_for_request'
  end

images_controller.rb:

<h2>Make Response Image</h2>
# Send this form for image to image controller with request_id of this request
<%= form_for [@request, @request.response_images.build], url: url_for(action: 'create_for_request') do |f|  %>
<p>

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

您在表单中提到了@request.images.build,但我没有看到您有任何关联,例如请求has_many :images,而您还有其他几个涉及图片的关联。我不知道你想要在那里建立哪种关联,所以我只能建议将build更改为你想要的实际关联,而且你可能需要根据这一点调整你的create_for_request

编辑: OP在发布的问题中更改了@request.images.build行以解决问题。并且在这个答案的评论部分中提到的他的新问题的解决方案是更改表单声明中的controller。因为您指的是a action控制器中不存在的Request