Search code examples
ruby-on-railsroutesreddit

Rails nested routes


I am learning Rails and making a reddit clone to help me understand how routing works.

Each post has subreddit. I have the following in my routes file:

resources :subreddits  do
 resources :posts
end 

This way I can create new posts with the following url:

/subreddits/:subreddit_id/posts/new(.:format)

Example:

http://localhost:3000/subreddits/1/posts/new

However I still need to specify in the new posts form what subreddit I want to post to belong to. Wheras what I want is a hidden field that sets the subreddit id to the correct one. The correct one being the one given in the URL.

This is what I currently have:

=simple_form_for @post, html: {multipart: true} do |f|
-if @post.errors.any?
    #errors
        %h2
        =pluralize(@post.errors.count, "error")
        prevented this pin from saving
        %ul
            [email protected]_messages.each do |msg|
                %li= msg


.form-group
    =f.input :title, input_html: {class: 'form-control'}

.form-group
    =f.input :content, input_html: {class: 'form-control'}

=f.hidden_field :subreddit_id, :value => @post.subreddit_id

=f.button :submit, class: "btn btn-primary"

I get the following error:

No route matches {:action=>"show", :controller=>"posts", :id=>33, :subreddit_id=>nil} missing required keys: [:subreddit_id]

I think this is because I am trying to access the subreddit id of a post that hasn't been created yet. How do I solve this? Am I going about it in the wrong direction?


Solution

  • In the new action of the posts_controller, you'll set the @subreddit instance variable

    def new
      @subreddit = Subreddit.find(params[:subreddit_id])
      @post = Post.new
    end
    

    In the form, you'll need to change the first line

    = simple_form_for [@subreddit, @post], html: {multipart: true} do |f|
    

    :subreddit_id will now be in the url