Assign ID at time of creation

Asked

Viewed 22 times

0

Guys, I’m starting with Rails and I got a question.

I need to assign the ID of a "father" when creating your "children". For example, a blog has_many Posts.

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

Thank you.

1 answer

0


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

Basically in his 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.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.