我有一个约会对象和一个预订对象。预订属于日程安排和日程安排has_many bookings。
我想在创建时将约会ID传递给bookings.appointment_id。我该怎么做呢?
*我已经根据jordanandree的建议编辑了代码。现在我得到以下错误:
NoMethodError in BookingsController#new
undefined method `bookings' for nil:NilClass 在我的主页视图中,我有:
<% @appointments.each do |appointment| %>
<%= link_to "new Booking", new_appointment_booking_path(appointment)%>
<%end%>预订控制器:
def new
@booking = @appointment.bookings.new
...
def create
@booking = @appointment.bookings.new(params[:booking])
...路线
resources :appointments do
resources :bookings
end非常感谢您的帮助。
Rake路由:
POST /appointments/:appointment_id/bookings(.:format) bookings#create
GET /appointments/:appointment_id/bookings/new(.:format) bookings#new
GET /appointments/:appointment_id/bookings/:id/edit(.:format) bookings#edit发布于 2012-09-30 01:06:29
Rails关联允许您基于现有记录创建记录。您当前拥有的是从表单传递到控制器的参数,这有点过度了。
例如,您可以更改create方法,使其遵循为预订和约会模型声明的相同关联模式:
@booking = @appointment.bookings.new(params[:booking])这将获取已经存在的@appointment记录的id,并在新的@booking实例变量上设置它。
另外,我也会看看nested resource routing。不确定这两个型号的路由当前是什么样子,但可能是这样的:
resources :appointments do
resources :bookings
end这将为您拥有new_booking_path的表单提供一种更干净的方法。它将更改为new_appointment_booking_path(@appointment)。这将把约会的ID传递给您的预订控制器,您可以在那里为约会创建关联的记录。
https://stackoverflow.com/questions/12654539
复制相似问题