Ruby on rails RubyonRails-需要帮助关联模型吗

Ruby on rails RubyonRails-需要帮助关联模型吗,ruby-on-rails,model-associations,rails-models,Ruby On Rails,Model Associations,Rails Models,好吧,我仍然是RubyonRails的新手,试图学习我的方法。我有两个模型(用户模型和评论模型)。基本上,用户有一个简单的个人资料,在同一页上有“关于我”部分和照片部分。用户必须登录才能对其他用户配置文件发表评论 我的用户模型 class User < ActiveRecord::Base attr_accessible :email, :name, :username, :gender, :password, :password_confirmation

好吧,我仍然是RubyonRails的新手,试图学习我的方法。我有两个模型(用户模型和评论模型)。基本上,用户有一个简单的个人资料,在同一页上有“关于我”部分和照片部分。用户必须登录才能对其他用户配置文件发表评论

我的用户模型

    class User < ActiveRecord::Base
        attr_accessible :email, :name, :username, :gender, :password, :password_confirmation
        has_secure_password
        has_many :comments
        .
        .
    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 
我想从
commenter\u id
获取用户的名称,但当我尝试类似
comment.commenter.name
的操作时,它会不断抛出错误
未定义的方法“commenter”。但是,
comment.user.name
工作正常,但它不会返回我想要的内容。我猜我没有正确地理解这些联想

我需要帮助在模型中获得正确的关联,以便从注释者id中获得名称

我的最后一个问题是,如何捕捉评论表单中的错误?这不是(@user)
通常的
表单,您喜欢
@user.errors.any?

routes.rb

      resources :users do
         resources :comments, only: [:create, :destroy]
      end

在您的模型中尝试类似的东西

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
class用户“Comment”,:foreign\u key=>“user\u id”
有很多:给定注释,:class\u name=>“Comment”,:foreign\u key=>“commenter\u id”
结束
类注释“User”,:foreign\u key=>“commenter\u id”
结束
退房:

您可能会在网站上找到更好的命名方法,因为我收到的和收到的许多收藏都是我在短时间内所能做到的最好的:)

注意:外键在很多情况下都是可选的,把它留在上面-我认为它有助于清晰

  • _many fk是否引用了many表(其他表)中的列
  • 属于\u to fk指多表(此表)中的列

在您的评论类中,您可以添加一个带有自定义名称和外键的“自定义”关系:
属于:commenter,外键:'user\u id',class\u name:'user'
请参见此处:(他们与个人作者和帖子的示例)使用我给您的内容,您应该能够执行
评论。commenter
并且如果存在,应该返回一个用户对象
      def show
        @user = User.find(params[:id])
        @comments = @user.comments
      end
      resources :users do
         resources :comments, only: [:create, :destroy]
      end
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