我在rails 3.1 app中有两个模型:lease_booking和lease_log。 Lease_booking has_many lease_logs和lease_log belongs_to lease_booking。在routes.rb中,关联是:
resources :lease_bookings do
resources :lease_logs
end
在lease_booking show.html.erb中,创建新租约日志的路径是:
<%= link_to "new Log", new_lease_booking_lease_log_path(@lease_booking) %>
lease_log控制器中的“新”代码是:
def new
@lease_log = LeaseBooking.find(params[:id]).lease_log.new()
end
但是,点击“新建日志”后,lease_log控制器“new”出错:
Couldn't find LeaseBooking without an ID
租赁日志控制器似乎未正确识别租赁预订的ID(应为1)。
同一错误页面上的租约预订ID(1)是正确的:
Parameters:
{"lease_booking_id"=>"1"}
有没有办法解决它?感谢。
更新:这是佣金路线的输出
lease_booking_lease_logs GET /lease_bookings/:lease_booking_id/lease_logs(.:format) {:action=>"index", :controller=>"lease_logs"}
POST /lease_bookings/:lease_booking_id/lease_logs(.:format) {:action=>"create", :controller=>"lease_logs"}
new_lease_booking_lease_log GET /lease_bookings/:lease_booking_id/lease_logs/new(.:format) {:action=>"new", :controller=>"lease_logs"}
edit_lease_booking_lease_log GET /lease_bookings/:lease_booking_id/lease_logs/:id/edit(.:format) {:action=>"edit", :controller=>"lease_logs"}
lease_booking_lease_log GET /lease_bookings/:lease_booking_id/lease_logs/:id(.:format) {:action=>"show", :controller=>"lease_logs"}
PUT /lease_bookings/:lease_booking_id/lease_logs/:id(.:format) {:action=>"update", :controller=>"lease_logs"}
DELETE /lease_bookings/:lease_booking_id/lease_logs/:id(.:format) {:action=>"destroy", :controller=>"lease_logs"}
答案 0 :(得分:2)
您的参数输出显示了您应该寻找的shat参数 - lease_booking_id:
@lease_log = LeaseBooking.find(params[:lease_booking_id]).lease_log.new()
在控制台中,运行rake routes
以查看嵌套路由如何使用参数。
编辑:
当您嵌套路线时,内部资源取决于外部资源:
resources :lease_bookings do
resources :lease_logs
end
查看用于创建lease_log的rake routes
输出:
POST /lease_bookings/:lease_booking_id/lease_logs
因此,当您设置表单时,您需要指定lease_booking以及新的lease_log(并且需要相应地调整任何_path或_url方法):
<%= simple_form_for [@lease_booking, @lease_log] do |f| %>
这还需要您在控制器中设置@lease_booking:
有关Rails路由的详细信息,请参阅http://guides.rubyonrails.org/routing.html。
def new
@lease_booking = LeaseBooking.find(params[:lease_booking_id])
@lease_log = @lease_booking.lease_log.new
end
答案 1 :(得分:0)
这是我发现构建一对多关联的控制器和视图的完美示例:
http://jonathanhui.com/ruby-rails-3-model-1-many-association