Ricky Ahn
Ricky Ahn

Reputation: 191

Rails 4 - railscast #154 polymorphic association

Im following ryan bates screen cast on polymoprhic associations

http://railscasts.com/episodes/154-polymorphic-association-revised?view=asciicast

I've done this sucessfully before on a Rails 3 app but now im on Rails 4 and i feel like im having issues with strong parameters..... but i can be wrong

when i go into my console to create a new event for a user it works

a = Event.first
c = a.events.create!(name: "Hello World")

this works and posts on my events index page

howwever when i try to use the actual form on the site it creates the record but the name field is nil and blank...and i dont get any errors

heres my controller (im basically just copying what Ryan Bates does on the site)

class EventsController < ApplicationController
before_filter :load_eventable
def index
  @eventable = Admin.find(params[:admin_id])
  @events = @eventable.events
end

def new
  @event = @eventable.events.new
end

def create
  @event = @eventable.events.new(params[:events])
  if @event.save
    redirect_to [@eventable, :events], notice: "Event created."
  else
    render :new
  end
end

private
  def load_eventable
    resource, id = request.path.split('/')[1,2]
    @eventable = resource.singularize.classify.constantize.find(id)
  end

  def events
    params.require(:events).permit(:name, :address, :city, :state, :zip, :date, :time, :admin_id)
  end
end

here my form (very simple and im just using name for now)

= form_for [@eventable, @event] do |f| 
  .field 
    = f.text_field :name
    = f.submit

Upvotes: 1

Views: 1291

Answers (1)

Momer
Momer

Reputation: 3237

Try the below: creating a new event with the event_params method you defined instead of the params hash. I changed the name to make it a little less confusing.

class EventsController < ApplicationController

  ...
  def create
    @event = @eventable.events.new(event_params)
    if @event.save
      redirect_to [@eventable, :events], notice: "Event created."
    else
      render :new
    end
  end

  private
    ...

    def event_params
      params.require(:events).permit(:name, :address, :city, :state, :zip, :date, :time, :admin_id)
    end
end

Upvotes: 2

Related Questions