lundi 6 juillet 2015

Create/update validation for model with multiple controllers

I have a Rails app that has an organization model that stores information on several different types of organizations (distributors, dealers, customers, etc.) within my application.

During the early days of this app, one controller was used to perform all of the CRUD operations for this organization model but as the app grew, there became a need to implement separate controllers for each organization type stored by the organization model (e.g. a distributors controller, dealers controller, etc.).

I have managed to make this work within the form by using the url parameter inside form_for but I'm running into problems making the validation work for either the create or update methods. When I attempt to render the new/edit methods (which have routes) as a result of an invalid/incomplete model to show validation, I receive a routing error for the controller I'm attempting to create/update organizations with, which looks like:

No route matches {:controller=>"distributors"}

My controller create/update methods are pretty vanilla Rails and resemble what scaffolding generators generate:

def create
  @organization = Organization.new(params[:organization])
  if @organization.save
    redirect_to @organization, notice: t('flash.organization.created')
  else
    render action: 'new'
  end
end

I've determined that my problem is on the line where I attempt to render the "new" method and I'm guessing that "new" is too ambiguous. I've tried a couple different approaches here including...

render 'distributors/new'

...and...

render :new

...and...

render action: 'new', template: "#{Rails.root}/app/controllers/distributors"

...but none of these appear to work.

I get that what I'm attempting to do here is kind of an anti-patern but is there a way to make this work? I'm not sure why an exception would be raised that suggests that the routes aren't in place, which they are. What am I doing wrong?

Thanks in advance...

Aucun commentaire:

Enregistrer un commentaire