當我嘗試創建新數據時,顯示以下錯誤。Rails:ActionController :: UrlGenerationError,沒有路由匹配,缺少必需的鍵
ActionController::UrlGenerationError (No route matches {:room_id=>nil, :action=>"index", :controller=>"events"} missing required keys: [:room_id]):
模式
models/rooms.rb
has_many :events, inverse_of: :room, dependent: :destroy
has_many :amounts, inverse_of: :room, dependent: :destroy
accepts_nested_attributes_for :events, allow_destroy: true
models/events.rb
has_one :amount, inverse_of: :schedule, dependent: :destroy
accepts_nested_attributes_for :amount, allow_destroy: true
的routes.rb
...
resources :events, only: [:new, :create, :edit, :update]
resources :rooms do
resources :events
end
...
當我點擊link_to
爲new_room_event_path(1)
,顯示上面的錯誤。 它生成root/rooms/1/events/new
。
視圖
<% if logged_in? %>
<% if current_user?(@user) %>
<% if schedule.rooms.blank? %>
<%= link_to "Add event", new_room_event_path(1), class: "btn btn-sn btn-primary" %>
<br>
<% end %>
<% end %>
<% end %>
爲什麼我指定new_room_event_path(1)
的原因是,這是第一次來創建數據。
events_controller.rb
before_action :load_room
def new
@event = Event.new
@event.room = @room
@event.build_amount
@event.amount.schedule = @room.schedule
@event.amount.room = @room
end
private
def load_room
if Room.exists?(id: params[:room_id])
@room = Room.find(params[:room_id])
else
@room = Room.new
end
end
如果你能給我任何建議,這可以理解。
它是否創建了至少一個房間?因爲你似乎在傳遞硬編碼價值,所以我問這個... – SnehaT