Jump to content

The ultimate community for Ruby on Rails developers.


How to proceed...

  • Please log in to reply
1 reply to this topic

#1 Igor



  • Members
  • 1 posts

Posted 02 September 2013 - 09:34 PM

I have these models:


class History < ActiveRecord::Base
  has_many :stories
  has_many :lanes
class Lane < ActiveRecord::Base
  belongs_to :history
class Story < ActiveRecord::Base
  belongs_to :history
I'd like to create a Story inside a lane, but the relationship is not store - lane directly so I need a new_story_path which is able to pass the lane object and inside the new method of controller I could be able to generate a new History passing the lane and the story and persist: store and history ..
How could I proceed?

#2 james



  • Members
  • 223 posts
  • LocationLeeds, U.K.

Posted 02 September 2013 - 10:46 PM

There are many ways to achieve this but possibly the simples for you would be to use nested routes


A brief excerpt from the rails guides http://guides.rubyon...rg/routing.html



2.7.1 Limits to Nesting

You can nest resources within other nested resources if you like. For example:

resources :publishers do
  resources :magazines do
    resources :photos

Deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize paths such as:


The corresponding route helper would be publisher_magazine_photo_url, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular article by Jamis Buck proposes a rule of thumb for good Rails design:

Resources should never be nested more than 1 level deep.

2.7.2 Shallow Nesting

One way to avoid deep nesting (as recommended above) is to generate the collection actions scoped under the parent, so as to get a sense of the hierarchy, but to not nest the member actions. In other words, to only build routes with the minimal amount of information to uniquely identify the resource, like this:

resources :posts do
  resources :comments, only: [:index, :new, :create]
resources :comments, only: [:show, :edit, :update, :destroy]

This idea strikes a balance between descriptive routes and deep nesting. There exists shorthand syntax to achieve just that, via the :shallow option:

resources :posts do
  resources :comments, shallow: true

This will generate the exact same routes as the first example. You can also specify the :shallow option in the parent resource, in which case all of the nested resources will be shallow:

resources :posts, shallow: true do
  resources :comments
  resources :quotes
  resources :drafts

The shallow method of the DSL creates a scope inside of which every nesting is shallow. This generates the same routes as the previous example:



Programming is just about problem solving!

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users