不使用嵌套资源命中控制器方法

时间:2016-06-29 16:51:51

标签: ruby-on-rails model-view-controller routing erb

我为特定列表创建了一个开放日。我现在正在尝试添加RSVP功能。我一直收到错误,但我无法弄清楚。我确定这是愚蠢的,但我只是没有看到它。

Rake Routes:

rsvp_listing_open_house GET  /listings/:listing_id/open_houses/:id/rsvp(.:format)  open_houses#rsvp                   

我的路线:

resources :listings do
  member do
    get 'like'
    get 'unlike'
    get 'duplicate'
    get 'gallery'
    delete 'gallery' => 'listings#clear_gallery'
    get 'manage_photos'
    get 'craigslist'
    get "add_to_collection"
    get 'request_photos'
  end
  resources :open_houses do
    member do
      get 'rsvp'
    end
  end
  resources :listing_feedbacks do
    member do
      get 'archive_feedback'
    end
  end
end

我的控制器:

def rsvp
  @open_house_rsvp = params[:open_house_rsvp]
  agent_id = params[:agent_id]
  open_house_id = params[:open_house_id]
  OpenHouseRsvp.create(:agent_id => agent_id, :open_house_id => open_house_id )
  flash[:notice] = "Your RSVP has been submitted!"
  redirect_to listing_open_houses_path
end

查看:

<%= link_to "RSVP", rsvp_listing_open_house_path %>

错误:

ActionController::UrlGenerationError in OpenHouses#index

No route matches {:action=>"rsvp", :controller=>"open_houses", :listing_id=>"5341"} missing required keys: [:id]

2 个答案:

答案 0 :(得分:1)

根据提供的错误,路径助手已经收到:listing_id,并且期望来自打开的房屋对象的:id,以便它可以正确地构建路径。假设您的控制器中定义了@open_house对象,您的路径助手应如下所示:

<%= link_to "RSVP", rsvp_listing_open_house_path @open_house %>

希望这有帮助!

答案 1 :(得分:0)

我没有足够的声誉发表评论,所以只是总结Zoran和Nic上面的评论:

  • rsvp_listing_open_house_path需要2个参数: listing_id open_house_id ,您可以使用rsvp_listing_open_house_path(@listing, @open_house)rsvp_listing_open_house_path(@listing.id, @open_house.id)
  • 确保您的控制器操作中有 @listing @open_house (您可以用不同的名称命名)。否则,您将收到评论中提到的错误:No route matches {:action=>"rsvp", :controller=>"open_houses", :id=>nil, :listing_id=>nil} missing required keys: [:id, :listing_id]