Micropost's comments on users page (Ruby on Rails)

后端 未结 2 541
自闭症患者
自闭症患者 2020-12-15 02:17

On user\'s page i have many microposts and i want to add comment form and comments to each micropost.

I have three models: User, Micropost, Comment.

相关标签:
2条回答
  • 2020-12-15 02:56

    Try passing in the current micropost to the comment partial

    <%= render 'shared/comment_form', micropost: micropost %>
    

    Then add the micropost to the comment form_for call

    <%= form_for([micropost, @comment]) do |f| %>
    

    Make sure your routes are nested

    # in routes.rb
    resources :microposts do
      resources :comments
    end
    

    Then build the comment off of the micropost in the CommentsController

    def create
      @micropost = Micropost.find(params[:micropost_id])
      @comment = @micropost.comments.build(params[:comment])
      ...
    end
    
    0 讨论(0)
  • 2020-12-15 02:56

    I would use nested resources for micropost and comments like this in your routes.rb file:

    resources :microposts do
      resources :comments
    end
    

    Then in your comments controller, which you access through the micropost_comments_path(@micropost) url helper you can do the following to build the association in the create action:

    def create
      @micropost = Micropost.find(params[:micropost_id])
      @comment = Comment.new(params[:comment])
      @comment.micropost = @micropost
      @comment.user = current_user
    
      if @comment.save
        ...
    end
    

    You could reduce the number of lines of code using the merge method, but I find that this sometimes reduces the readability of your code, and since you'll need the @micropost object if redisplaying the form after validation errors you may as well just fetch the record.

    0 讨论(0)
提交回复
热议问题