Rails 4 - BookingsController中的NoMethodError#在使用嵌套资源时创建

时间:2014-07-18 16:42:23

标签: ruby-on-rails ruby ruby-on-rails-4

我正在使用Ruby on Rails 4.1为我的示例项目创建一个票务预订应用程序。三个是三个模型 - 活动,门票和预订。活动有很多门票和预订。门票有很多预订,属于活动。预订属于活动和门票。

以下是嵌套路线的样子:

resources :events do
  resources :tickets
  resources :bookings
end

票证控制器工作得很好,这是控制器代码:

class TicketsController < ApplicationController
def index
    @event = Event.find(params[:event_id])
    @tickets = @event.tickets.all
end

def show
    @event = Event.find(params[:event_id])
    @ticket = @event.tickets.find(params[:id])
end

def new
    @event = Event.find(params[:event_id])
    @ticket = Ticket.new
end

def create
    @event = Event.find(params[:event_id])
    @ticket = @event.tickets.create(ticket_params)
    if @ticket.save
        redirect_to [@event, @ticket]
    else
        render 'new'
    end
end

def edit
    @event = Event.find(params[:event_id])
    @ticket= @event.tickets.find(params[:id])
end

def update
    @event = Event.find(params[:event_id])
    @ticket = @event.tickets.find(params[:id])

    if @ticket.update(ticket_params)
        redirect_to [@event, @ticket]
    else
        render 'edit'
    end
end

def destroy
    @event = Event.find(params[:event_id])
    @ticket = @event.tickets.find(params[:id])
    @ticket.destroy
    redirect_to event_tickets_path
end


private

def ticket_params
    params.require(:ticket).permit(:ticket_name, :booking_start_date, :booking_end_date, :ticket_price, :ticket_quantity, :minimum_quantity, :maximum_quantity, :terms_conditions, :more_information)
end

但是,当我按照步骤创建预订控制器时,收到错误消息:

NoMethodError in BookingsController#create

undefined method `bookings' for #<Event:0x007f84dd6cc7a8>

预订控制器如下所示:

class BookingsController < ApplicationController
def new
 @event = Event.find(params[:event_id])
 @booking = Booking.new
end

def create
  @event = Event.find(params[:event_id])
  @booking = @event.bookings.create(booking_params)
  if @booking.save
    redirect_to [@event, @booking]
  else
    render 'new'
  end
end

def show
  @event = Event.find(params[:event_id])
  @booking = @event.bookings.find(params[:id])
end

private

def booking_params
  params.require(:booking).permit(:buyer_name, :email, :mobile, :address, :order_quantity)
end
end

有人能让我知道我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

我认为您忘记在事件方面声明事件和预订之间的关系:确保您拥有以下has_many

class Event < ActiveRecord::Base
  has_many :bookings
  # etc.