简体   繁体   中英

Ruby on Rails and Devise associating id from one table to a foreign_key id in another table

I have created a user model using devise. In the comment model I set the comment belongs_to :user . Within the user model, I then set the has_many: comments relationship.

comment model

class Comment < ActiveRecord::Base
  belongs_to :user
end

user model

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :comments
end

Inside the comment controller, I have the following code.

class CommentsController < ApplicationController

  def create
    @comment = Comment.new(params[:comment])
    @comment.user = current_user
    if @comment.save

    end
  end

......

end

In the view within the index page I have this code inside an erb basically to pull the name of the user

<td><%= comment.user.first_name if comment.user %></td> 

but it's not displaying anything at all?

Basically I have tables in the database, the User table and Comment table. I would like to associate the id of the user from the User table with the foreign_key , user_id in the comment table.

For example, I have logged in as a user with user id = 1 and created a comment. When I queried the database to check the comment the user_id was nil

#<Comment id: 19, Ticker: "Hello", MyComment: "Test", created_at: "2014-06-07 20:07:44", updated_at: "2014-06-07 20:07:44", user_id: nil>

I think you should have this;

class CommentsController < ApplicationController

  def create
    @comment = Comment.new(params[:comment])
    @comment.user_id = current_user.id
    if @comment.save

    end
  end

......

end

Then successfully call this;

<td><%= comment.user.first_name if comment.user %></td>

This is because @comment contain only the user reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM