我在 Ruby on Rails 中有一個一對多的關聯:
class Booking < ActiveRecord::Base
has_many :rides
accepts_nested_attributes_for :rides, allow_destroy: true
end
### and ###
class Ride < ActiveRecord::Base
belongs_to :bookings
end
預訂和乘車視圖和控制器是腳手架。
我想在我的預訂表格中添加一個“添加游樂設施”按鈕:
= simple_form_for(@booking) do |f|
= f.error_notification
= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present?
.form-inputs
.container
.row
.col-6
= f.input :first_name
= f.input :phone_number
.col-6
= f.input :last_name
= f.input :email
.col-12
= f.input :company
### here is the simple fields that does not work:
= f.simple_fields_for :rides do |ride|
= render 'rides/form', :f => ride
= link_to_add_association 'add ride', f, :rides
但是,什么都沒有顯示,我不知道為什么。
我嘗試過的事情:
- 添加
rides_build我嘗試將其添加到預訂控制器
def new
@booking = Booking.new
@booking.build_rides
end
但它只給了我一個錯誤“#Booking:0x000000010575c578 的未定義方法`build_rides'”
- 添加
rides.build
def new
@booking = Booking.new
@booking.rides.build
end
這也給了我一條錯誤訊息:“nil:NilClass 的未定義方法‘model_name’”
- 僅添加
ride
def new
@booking = Booking.new
@booking.build
end
這只是沒有做任何事情。沒有錯誤,但問題沒有解決。
- 更改
ApplicationRecord為ActiveRecord::BaseThis 為其他人解決了它,但不是為我。
可能還想補充一點,在 simple_fields_for 中絕對不會渲染任何內容,即使是簡單的h1.
uj5u.com熱心網友回復:
選項 2 是正確的方法,應該可以作業,但是你的Ride模型有錯誤,它應該說
belongs_to :booking
注意:simple_fields_for對嵌套子級的迭代,只要沒有,就不會渲染任何內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441504.html
