【问题标题】:Creating a created_by column and association with rails?创建 created_by 列并与 rails 关联?
【发布时间】:2010-11-21 20:27:14
【问题描述】:

叹息...我觉得这个是个大新手,所以假设我有几个模型:

class Question < ActiveRecord::Base
  has_many :answers
  belongs_to :user
end

class Answer < ActiveRecord::Base
  belongs_to :question
  has_one :user
end

class User < ActiveRecord::Base
  has_many :questions
  has_many :answers, :through => :questions
end

所以我的问题是我不知道如何获取创建问题或答案的用户,应该在创建问题(或创建答案)时确定用户,并且用户应该来自当前用户会话(来自 authlogic 的用户模型和控制器)请参见此处:

class ApplicationController < ActionController::Base

  helper_method :current_user_session, :current_user

  ...

  private

  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end

  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.user
  end

end

现在,current_user 辅助方法工作正常,但我如何设置创建问题或答案的用户?喜欢 id 喜欢说@question.user

顺便说一句,我的问题架构有一个 created_by 列,但是当我创建一个新问题时,它保持为空。

【问题讨论】:

  • 我意识到我想使用 created_by 列,但不确定为什么关联不起作用,并且该列保持为空。

标签: ruby-on-rails ruby activerecord model associations


【解决方案1】:

关联视图的另一种方式(Rails 4 和 5)

belongs_to :created_by, class_name: "User", foreign_key: "created_by_id"

如果需要两个或多个与一个类(即“用户”)的关联。

示例: 我想创建 User(:email, :password) 并将其与 profile(:name, :surname) 关联。但我还想为用户添加一个功能,可以使用他们的 :emails 创建其他用户的个人资料(并进一步向他们发送邀请)。

  1. 创建个人资料(belongs_to 用户)和用户(has_one 个人资料)。此关联在 Profiles 表中创建 user_id 列。

  2. 在生成的 Profiles 表迁移文件中添加以下行:

    t.belongs_to :user, index: true, optional: true
    

    所以关联变成:

    “用户 1 - 1..0 个人资料”,一种关系(因此个人资料可能有也可能没有 user_id

  3. 将顶部提到的关联添加到 Profile 模型。

    belongs_to :created_by, class_name: "User", foreign_key: "created_by_id" 
    
  4. 在 Profile#create 操作中添加 @user.created_by = current_user

【讨论】:

    【解决方案2】:

    与其调用列created_by,不如将​​列命名为user_id。将这些名称用于外键将使 rails 自动“看到”关联。

    在控制器中设置属性的一种简单方法是使用块:

    @question = Question.new(params[:question]) do |q|
    q.user_id = current_user.id
    end
    @question.save
    

    【讨论】:

    • 啊,太棒了,所以我明白了...这将当前用户的 id 放在该字段中。但是,我确实违背了您的建议并使用了 created_by 列。
    • 当然这听起来很愚蠢......但在我看来,我不确定如何访问用户? question.created_by.username 不起作用。但是 question.created_by 给了我用户的 ID。想法?
    • 如果你要调用列 created_by,你需要指定列的名称,因为它默认假定它被称为 user_id (belongs_to :user, :foreign_key => "created_by " ) 然后您可以访问该关联用户:(question.user.username)
    • 哇,它比我想象的要简单得多,我的问题主要出在我定义的关联上: has_one :user, :through => :created_by, :foreign_key => "created_by"
    • 我猜你的意思是一个答案 belongs_to :user。说 answer has_one :user 意味着您的用户表有一个引用答案的列,这很奇怪。此外,通过说用户 :has_many :answers :through :questions 表示用户 B 针对用户 A 的问题发布的答案属于用户 A。我不确定这是否是您想要的行为.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    相关资源
    最近更新 更多