Rails 3 - Creating a New Record not working
Scenario: I have an EventsController with a new event record. Depending on what I want to do with that event/record, I may need to create a new Ticket Record.
class Ticket < ActiveRecord::Base
belongs_to :event
class Event < ActiveRecord::Base
has_many :tickets
In my EventController, I have a method for eg.
def do_something
@event = Event.find(params[:id])
# I would like to create a Ticket record here
end
I have tried the following in my method:
@ticket = Ticket.new(:event_id => @event.id)
@ticket.ticket_name = @event.event_name
@ticket.ticket_quantity = 1000
@ticket.ticket_price = 0
@ticket.save
The above does absolutely nothing. I don't even get any errors in my log. as well as this:
Ticket.create!(
:event_id => @eve开发者_开发知识库nt.id,
:ticket_name => @event.event_name,
:ticket_quantity => 1000,
:ticket_price => 0 )
For this one: I get: ActiveRecord::RecordInvalid (Validation failed: Event is not allowed to create Tickets):
I'm not sure if I'm even doing in the right place or not. Thanks
With your current model associations the correct way to create a new Ticket
is through the Event
object. Like this:
@ticket = @event.tickets.create(:ticket_name => @event.event_name,
:ticket_quantity => 1000,
:ticket_price => 0)
Note that you don't have to specify the event_id
.
For a more in depth explanation take a look at active record associations.
On a side note, in your Event
controller if you do save!
that should throw errors for you as well. Adding the bang !
will do a validation and if it fails, throw an error.
Execute
rails console
in your command line, try to create Ticket object there and see what output you get, then post it here, it would help to figure out what's the problem.
Also you can look at
@ticket.errors
in your debugger to see if there are any.
精彩评论