Robert
Robert

Reputation: 311

Can someone explain to me what the code below is doing?

I am working on a Rails tutorial and I have no idea what

@comment.article_id = params[:article_id]

is doing in the code:

 def create
    @comment = Comment.new(comment_params)
    @comment.article_id = params[:arcticle_id]
    @comment.save
    redirect_to article_path(@comment.article)
 end

Also, does the params[:article_id] get transferred into the instance variable on the left ?

Upvotes: 0

Views: 85

Answers (2)

Vivek
Vivek

Reputation: 949

You need to read about Rails "Active Record Associations"

class Article < ApplicationRecord
  has_many :comments, dependent: :destroy
end

class Comments < ApplicationRecord
  belongs_to :article
end

When you create has_many and belongs_to relation between two tables you need to store article.id in comments table then comments related to that particular article.

In your code:

def create
    @comment = Comment.new(comment_params)
    @comment.article_id = params[:arcticle_id]

    @comment.save

    redirect_to article_path(@comment.article)
end

You are creating comment for an article so when you do

@comment.article_id = params[:arcticle_id]

it will store the article.id in this comment so this comment related to that particular article.

Read Active Record Associations

Upvotes: 1

Corey Gibson
Corey Gibson

Reputation: 343

since you are using a relational database the 'artical_id' is used to create a relation between the comment and the article that it belongs to.

So the code:

@comment.artical_id = params[:artical_id]

is used to give the comment it's article id so it can be referred back to later.

Hope this help

Upvotes: 0

Related Questions