1

So, essentially, I have two models, Ticket

class Ticket < ActiveRecord::Base
    belongs_to :event
end

And Event:

class Event < ActiveRecord::Base
    belongs_to :club
    has_many :tickets
    accepts_nested_attributes_for :tickets
end

They are associated with each other, and I have done the necessary migrations.

In the events/show view, it shows the event and then at the end I have a link to create a ticket, with this event's name passed as an id:

<%= link_to 'Add tickets', new_ticket_path(:id => @event.name) %>

This renders properly in the new ticket page, I have tested it in the new ticket view with <%= params[:id] %> and it comes up correctly.

The tickets_controller's create method is as follows:

def create
    @ticket = Ticket.new(ticket_params)
    @ticket.event_id = params[:id]
    ...
end

But when testing back in the events/show view

<% @tickets = Ticket.all %>
    <% @tickets.each do |ticket| %>
    <p><%= ticket.event_id %>--</p>
<% end %>

All of the event_id's come up empty.

Any suggestions?

tcatchy
  • 849
  • 1
  • 7
  • 17

1 Answers1

1

The problem is you're passing the :id param to the new method, and then expecting it to persist to the create method

Params are HTTP-based values -- they don't last longer than a single request. You'll have to either use a nested resource, or set the event_id attribute in your new form:


Route

#config/routes.rb
resources :events do
    resources :tickets #-> /events/:event_id/tickets/new
end

This will keep the params[:event_id] param consistent (as it's being passed in the URL), allowing you to use it in your create action like so:

def create
    @ticket = Ticket.new(ticket_params)
    @ticket.event_id = params[:event_id]
    ...
end

This is the conventional way to do this


Attribute

If you want to just test your code, you should set the event_id param in your new action form:

<%= form_for [@event, @ticket] do |f| %>
   <%= f.hidden :event_id, params[:id] %> #-> sets params[:ticket][:event_id]
<% end %>

This will allow you to set the event_id param in your strong_params method in your create action:

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

def create
   @ticket = Ticket.new(ticket_params)
   @ticket.save
end

private

def ticket_params
    params.require(:ticket).permit(:event_id)
end
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147