jshou
jshou

Reputation: 682

Rails 3 controller methods for nested resource don't run

I'm creating nested resources Foo and Bar where Foo has_many Bars and Bar belongs_to Foo

This is the new method in BarsController:

def new
  @foo = Foo.find(params[:foo_id])
  @bar = @foo.bars.build
end

This is the code for the Bar new view:

<%= form_for([@foo, @bar]) do |f| %>
  <%= f.text_field :name %>
  <%= f.submit "Save" %>
<% end %>

When I try to load the "new bar" page, rails says that the model_name method cannot be found for value Nil. Curiously, this slightly modified view code works:

<%= form_for([@foo, @foo.bars.build]) do |f| %>
  <%= f.text_field :name %>
  <%= f.submit "Save" %>
<% end %>

However, when I put a logger.debug statement inside the new method in BarsController, it never runs. rake routes says and the server log confirms that BarsController#new is the action being called, but why won't the code that's inside the new action run? Am I missing something here?

Upvotes: 1

Views: 810

Answers (1)

Amokrane Chentir
Amokrane Chentir

Reputation: 30385

Some changes you could make to make it work:

  1. Bars is nested in Foo not the opposite, so instead of BarsController you should write your new action inside your FoosController as follow:

     def new
        @foo = Foo.new
        @bar = @foo.bars.build
     end
    
  2. Inside your foo model you should have:

    accepts_nested_attributes_for :bars

  3. Your view:

    <%= form_for @foo do |f| %> 
      <%= f.fields_for :bars do |ff| %>
      <%= ff.text_field :name %>
      <%= f.submit %>
     <% end %>
    
  4. Don't forget the create action inside your FoosController:

FoosController

    def create    
      @foo = Foo.new(params[:foo])
        if @foo.save
          redirect_to @foo
        else 
          render :new
        end
    end

Finally, pay attention to the validations written in your models! For instance it is possible that some fields (that you forgot to fill during your tests) are necessary for your form to be valid! Happened to me recently!

Upvotes: 1

Related Questions