Search code examples
ruby-on-railsruby-on-rails-3has-manybelongs-to

What is the proper way to create an object with a belongs_to association?


I'm pretty new to rails, and I have some trouble getting the philosophy and finding the "proper" way to create an object as a dependency of an other one.

I have a Backlog model :

class Backlog < ActiveRecord::Base
  has_many :user_stories
end

and a UserStory model :

class UserStory < ActiveRecord::Base
  belongs_to :backlog
end

On the show action of the Backlog controller, I want to display a link to create a UserStory that belongs to the current Backlog. I want it to redirect to the UserStory creation form.

<%= link_to 'New User story', "???" %>

if I put new_user_story_path, it creates a new UserStory but does not add it to the Backlog.

How should I do ?

Thanks !


Solution

  • You need to have nested routes.

    app/config/rotues.rb

    CodeGlot::Application.routes.draw do
    
      resources :backlogs do
        resources :user_stories
      end
    
    end
    

    Then you need to have a nested link:

    index.html.erb # or whatever file

    <%= link-to "New user story", new_backlog_user_story_path(backlog) %>
    

    *make sure you have a varible backlog, otherwise the route will fail.

    app/controllers/user_stories_controller.rb

    before_filter :get_backlog
    
    def get_backlog
        if params[:backlog_id]
            @backlog = Backlog.find(params[:backlog_id])
        end
    end
    
    def new
    end
    

    app/views/user_stories/new.html.erb

    <div class="form">
    <%= form_for([@backlog, @user_stories]) do |f| %>
      <div class="actions">
        <%= f.submit "Submit",  :disable_with => "Submitting..." %>
      </div>
    <% end %>
    </div>
    

    app/models/backlog.rb

    accepts_nested_attributes_for :user_stories