当我试图创建一个新房间时,我从视图的第7行得到错误:
undefined method `rooms_path' for #<#<Class:0x007fb46b5db2a0>:0x007fb46b5d9ec8>
我有点困惑为什么我会得到这个错误。我已经在Room
和Facility
之间建立了一种关系,即每个设施都有许多房间。工具部分的工作没有bug,我已经能够创建/编辑/显示工具。
视图(视图/房间/new.html.erb)
<div class="panel panel-default">
<div class="panel-heading">
Create your beautiful room
</div>
<div class="panel-body">
<div class="container">
<%= form_for @room do |f| %>
<div class="form-group">
<label>Name</label>
<%=f.text_field :room_name, placeholder: "What is the name of the room?", class: "form-control", required: true%>
</div>
<div><%= f.submit "Create This Room", class: "btn btn-normal" %></div>
<%end%>
</div>
</div>
</div>
我的房间模型( model /room.rb):
class Room < ApplicationRecord
belongs_to :facility
validates :room_type, presence: true
validates :room_name, presence: true
end
My Facility model (models/facility.rb):
class Facility < ApplicationRecord
belongs_to :user
has_many :photos
has_many :rooms
validates :facility_name, presence: true
validates :address, presence: true
validates :license, presence: true
validates :phone, presence: true
def cover_photo(size)
if self.photos.length > 0
self.photos[0].image.url(size)
else
"blank.jpg"
end
end
end
我的房间控制器(Controller/RoomsControler.rb)
class RoomsController < ApplicationController
before_action :set_room, except: [:index, :new, :create]
def index
@facility = Facility.find(params[:facility_id])
@rooms = @facility.rooms
end
def new
@facility = Facility.find(params[:facility_id])
@room = @facility.rooms.build
end
end
路由(routes.rb)
Rails.application.routes.draw do
devise_for :users,
path: '',
path_names: {sign_in: 'login', sign_out: 'logout', edit: 'profile', sign_up: 'registration'},
controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'}
resources :users, only: [:show]
resources :facilities, except: [:edit] do
member do
get 'listing'
get 'pricing'
get 'features'
get 'services'
get 'types_care'
get 'photo_upload'
get 'room_upload'
end
resources :rooms, except: [:edit] do
member do
get 'listing'
get 'pricing'
get 'photo_upload'
end
end
resources :photos, only: [:create, :destroy]
end
end
我已经坚持了几天了,真的很感谢你的帮助:)提前谢谢!
发布于 2018-01-28 01:43:58
form_for
基于@room
的类生成url,不包含外部资源。因此,您必须使用以下语句显式地告诉Rails执行此操作:
<%= form_for [@room.facility, @room] do |f| %>
发布于 2018-01-28 09:48:12
由于路径是嵌套的,因此请为form_for
选择以下任一选项,而不是<%= form_for @room do |f| %>
<%= form_for @room, url: [@room.facility, @room] do |f| %>
<%= form_for @room, url: [:facility, @room] do |f| %>
<%= form_for [@room.facility, @room] do |f| %>
<%= form_for [:facility, @room] do |f| %>
Here您可以获得有关form_for
helper的更多详细信息
https://stackoverflow.com/questions/48480359
复制