2014-06-07 14 views
0

我已經使用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> 
+0

嘗試通過用戶建立 - '@comment = current_user.comments.build(params [:comment])''。但你現有的代碼*應該*工作。是否設置了current_user?在'Comment' - 'validates_presence_of:user'上添加驗證。 –

+0

添加完整的控制器代碼。 –

+0

@Damien我加了這個validates_presence_of:user,抱歉不太清楚它應該做什麼?現在閱讀這個http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of – cloudviz

回答

1

我認爲你應該有這個;

class CommentsController < ApplicationController 

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

    end 
    end 

...... 

end 

然後成功調用這個;

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

這是因爲@comment僅包含用戶引用。

+0

感謝您的解釋。我試過這不起作用。 – cloudviz

+0

@cloudviz,現在user_id是否存在?你遇到了什麼錯誤? – Acacia

+0

我沒有收到任何錯誤。我試圖在評論旁邊顯示用戶的名字,沒有任何錯誤,但因爲它沒有被關聯到評論,所以顯示空白的first_names。 – cloudviz

相關問題