我已經使用devise創建了一個用戶模型。在評論模型中,我設置了評論belongs_to :user
。在用戶模型中,我然後設置has_many: comments
關係。Ruby on Rails和Devise將一個表中的id關聯到另一個表中的foreign_key id
評論模型
class Comment < ActiveRecord::Base
belongs_to :user
end
用戶模型
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
裏面的評論控制器,我有下面的代碼。
class CommentsController < ApplicationController
def create
@comment = Comment.new(params[:comment])
@comment.user = current_user
if @comment.save
end
end
......
end
在索引頁我有一個ERB這裏面的代碼中的觀點基本上是拉動用戶
<td><%= comment.user.first_name if comment.user %></td>
的名稱,但它並不顯示任何內容?
基本上我有數據庫中的表,用戶表和評論表。我想將用戶表中用戶的ID與註釋表中的foreign_key
,user_id
相關聯。
例如,我以用戶id = 1的用戶身份登錄並創建了一條評論。當我查詢數據庫來檢查評論user_id是零
#<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>
嘗試通過用戶建立 - '@comment = current_user.comments.build(params [:comment])''。但你現有的代碼*應該*工作。是否設置了current_user?在'Comment' - 'validates_presence_of:user'上添加驗證。 –
添加完整的控制器代碼。 –
@Damien我加了這個validates_presence_of:user,抱歉不太清楚它應該做什麼?現在閱讀這個http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of – cloudviz