2013-02-02 59 views
0

好吧,我仍然是一個試圖學習我的方式在軌道上的紅寶石新手。我有兩個模型(用戶模型和評論模型)。基本上,用戶具有簡單的配置文件,在同一頁面上具有「關於我」部分和照片的部分。用戶必須登錄才能評論其他用戶個人資料。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_idcommenter_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 
+0

在你列註釋類,可以使用自定義名稱和外鍵添加「自定義」關係:'belongs_to:commenter,foreign_key:'user_id',class_name:'User'' – MrYoshiji

+0

請參閱:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ ClassMethods.html#method-i-belongs_to(他們的人作者和帖子的例子)隨着我給你你應該能夠做'comment.commenter',這應該返回一個用戶對象,如果存在 – MrYoshiji

回答

0

嘗試這樣的事情在你的模型

class User < ActiveRecord::Base 
    has_many :received_comments, :class_name => "Comment", :foreign_key => "user_id" 
    has_many :given_comments, :class_name => "Comment", :foreign_key => "commenter_id" 
end 

class Comment < ActiveRecord::Base 
    belongs_to :user # comment about profile 
    belongs_to :commenter, :class_name => "User", :foreign_key => "commenter_id" 
end 

退房:http://guides.rubyonrails.org/association_basics.html

你也許可以想出上的has_many收藏更好的命名,接獲並是最好的我可以在短時間內完成:)

注意:在很多情況下,foreign_key是可選的,將它留在上面 - 我認爲它有助於清晰度

  • 的has_many FK是指在許多表中的列(其它表)
  • belongs_to的FK指的是在許多表(此表)