好吧,我仍然是一個試圖學習我的方式在軌道上的紅寶石新手。我有兩個模型(用戶模型和評論模型)。基本上,用戶具有簡單的配置文件,在同一頁面上具有「關於我」部分和照片的部分。用戶必須登錄才能評論其他用戶個人資料。Ruby on Rails - 需要幫助關聯模型
我的用戶模型
class User < ActiveRecord::Base
attr_accessible :email, :name, :username, :gender, :password, :password_confirmation
has_secure_password
has_many :comments
.
.
end
我的評論模型
class Comment < ActiveRecord::Base
belongs_to :user
attr_accessible :content
.
.
end
在我的意見表,我有一個user_id
列,用於保存其檔案已經被評論和commenter_id
用戶的ID存儲用戶對配置文件進行評論的ID的列。
意見表
<%= form_for([@user, @user.comments.build]) do |f| %>
<%= f.text_area :content, cols: "45", rows: "3", class: "btn-block comment-box" %>
<%= f.submit "Comment", class: "btn" %>
<% end %>
我的評論控制器
class CommentsController < ApplicationController
def create
@user = User.find(params[:user_id])
@comment = @user.comments.build(params[:comment])
@comment.commenter_id = current_user.id
if @comment.save
.........
else
.........
end
end
end
這正常在數據庫中存儲兩個user_id
和commenter_id
。在顯示頁面上顯示用戶評論時,我的問題就出現了。我想獲取對特定配置文件發表評論的用戶的姓名。
在我的用戶控制
def show
@user = User.find(params[:id])
@comments = @user.comments
end
我想從commenter_id
用戶的名稱,但它不斷拋出的錯誤undefined method 'commenter' for #<Comment:0x007f32b8c37430>
當我嘗試類似comment.commenter.name
。然而,comment.user.name
工作正常,但它不會返回我想要的。我猜測沒有得到正確的協會。
我需要幫助在模型中獲取正確的關聯,以便從commenter_id獲取名稱。
我最後一個問題,我如何在評論表中發現錯誤?它不像通常的form_for(@user)
那樣你喜歡@user.errors.any?
。
路線。RB
resources :users do
resources :comments, only: [:create, :destroy]
end
在你列註釋類,可以使用自定義名稱和外鍵添加「自定義」關係:'belongs_to:commenter,foreign_key:'user_id',class_name:'User'' – MrYoshiji
請參閱:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ ClassMethods.html#method-i-belongs_to(他們的人作者和帖子的例子)隨着我給你你應該能夠做'comment.commenter',這應該返回一個用戶對象,如果存在 – MrYoshiji