Assign ID at creation time

1

Well, I'm starting with Rails and I'm left with a question.

I need to assign the ID of a "parent" when creating your "children". For example, A Blog has_many Posts.

The moment you click the create blog post button the Blog ID must be passed. localhost: 3000 / blog / new_post / 1 this 1 would be the blog id.

Thank you.

    
asked by anonymous 26.11.2016 / 05:30

1 answer

0

I believe that for your case you can use the concept of Nested Resources .

Basically in your routes.rb you will do something like:

resources :blogs do 
  resources :posts
end

This will create routes like:

blog_posts GET    /blogs/:blog_id/posts(.:format)          posts#index
                        POST   /blogs/:blog_id/posts(.:format)          posts#create
 new_blog_post GET    /blogs/:blog_id/posts/new(.:format)      posts#new
edit_blog_post GET    /blogs/:blog_id/posts/:id/edit(.:format) posts#edit
     blog_post GET    /blogs/:blog_id/posts/:id(.:format)      posts#show
                        PATCH  /blogs/:blog_id/posts/:id(.:format)      posts#update
                        PUT    /blogs/:blog_id/posts/:id(.:format)      posts#update
                        DELETE /blogs/:blog_id/posts/:id(.:format)

So you'll always have the blog ID as a reference in your accounts.

Warning Note that the helpers of urls will also change, post_path to blog_post_path for example always passing the blog reference as blog_post_path(@blog) .

    
28.11.2016 / 12:40