3

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

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 列,但是当我创建一个新问题时,它保持为空。

4

2 回答 2

7

关联视图的另一种方式(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 User)和用户(has_one Profile)。此关联在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. 添加@user.created_by = current_user个人资料#create action

于 2017-05-30T13:54:35.247 回答
3

而不是调用列created_by,首选方法是命名列user_id。将这些名称用于外键将使 rails 自动“看到”关联。

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

@question = Question.new(params[:question]) do |q|
q.user_id = current_user.id
end
@question.save
于 2009-08-22T07:02:00.707 回答