Search code examples
ruby-on-railsruby-on-rails-3nested-formsfields-for

Rails nested form with accepts_nested_attributes_for with an unfortunate model name


I have a Parent model named "Controller" (Mature app, and not my decision)

belongs_to :controller
accepts_nested_attributes_for :controller

Form:

= f.fields_for :controller do |c|
    = c.hidden_field :id, :value => @controller.id
    = c.text_field :slw_type

which doesn't get displayed.

= f.fields_for :literally_anything_else do |c|
    = c.hidden_field :id, :value => @controller.id
    = c.text_field :slw_type

if change the variable name to anything else, the form builds. I have a hunch that it's a rails specific reserved name.

Question:

What's the problem? and how can I make this work?

SOLVED:

The issue was that the parent model wasn't associated with the child model yet. My mistake for not providing all the information necessary.

This worked.

def new
    @controller = Controller.find(params[:controller_id])
    @inspection = Inspection.new(:controller => @controller)

Therefore my fields_for form builder also worked.


Solution

  • Pick some innocuous variable name. not_really_a_controller or whatever. Use that for your variable and your form. Then, in your actual controller (e.g. ActionController::Base descendent), rename the incoming param so the model doesn't know any different, like so:

    before_filter :filter_params
    
    private
     def filter_params
       if params[:not_really_a_controller]
         params[:controller] = params.delete(:not_really_a_controller)
       end
     end
    

    I've used this strategy for similar reasons in the past, though not specifically for controller. Worth a try though!