Ruby on Rails - nested associations - creating new records -


i'm learning rails (4.2 installed) , working on social network simulation application. have setup 1 many relation between users , posts , i'm trying add comments posts. after multiple tries , following documentation on rubyonrails.org ended following setup:

user model

  has_many :posts, dependent: :destroy   has_many :comments, through: :posts 

post model

  belongs_to :user   has_many :comments 

comment model

  belongs_to :user 

the comment initiated post show page, post controller has:

def show     @comment = comment.new   end 

now question is: in comments controller , correct way create new record. tried below , many others, without success.

def create      @comment = current_user.posts.comment.new(comment_params)     @comment.save      redirect_to users_path    end 

(current_user devise)

also, afterwards, how can select post corresponding comment?

thank you

you'll want create relation on post, letting each comment know "which post relates to." in case, you'll want create foreign key on comment post_id, each comment belong_to specific post. so, you'd add belongs_to :post on comment model.

so, models become:

class user < activerecord::base   has_many :posts, dependent: :destroy   has_many :comments, through: :posts end  class post < activerecord::base   belongs_to :user   has_many :comments end  class comments < activerecord::base   belongs_to :user   belongs_to :post end 

then, create comment, want 1 of 2 things in controller:

  1. load post corresponding comment creating via uri parameter.

  2. pass post id along in form in calls create method on comment.

i prefer loading post parameter in uri, you'll have less checking far authorization can comment in question added post - e.g. think of hacking form , changing id post form sets.

then, create method in commentscontroller this:

def create   @post = post.find(post_id_param)    # you'll want authorization logic here   # "can current_user create comment   # post", , perhaps "is there current_user?"    @comment = @post.comments.build(comment_params)    if @comment.save     redirect_to posts_path(@post)   else     # display errors , return comment     @errors = @comment.errors     render :new   end end   private  def post_id_param   params.require(:post_id) end  def comment_params   params.require(:comment).permit(...) # permit acceptable comment params here end 

Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

Simple Angular 2 project fails 'Unexpected reserved word' -

php - Get process resource by PID -