创建created_by列并与rails关联?

JP *_*shy 2 ruby activerecord model ruby-on-rails associations

igh ...我觉得这是一个新手,所以可以说我有几个型号:

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
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,我不知道如何获得创建问题或答案的用户,应该确定创建问题(或答案)的用户,并且该用户应来自当前用户的会话( (来自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
Run Code Online (Sandbox Code Playgroud)

现在,current_user帮助程序方法可以正常工作,但是如何设置由哪个用户创建问题或答案呢?像ID一样,只想说@ question.user

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

Lun*_*n4i 5

关联视图的另一种方法(第4和5条)

belongs_to :created_by, class_name: "User", foreign_key: "created_by_id"
Run Code Online (Sandbox Code Playgroud)

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

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

  1. 创建配置文件(属于User)和用户(has_one 配置文件)。该关联在“ 个人档案”表中创建user_id列。

  2. 在生成的“ 个人档案”表迁移文件中,添加以下行:

    t.belongs_to :user, index: true, optional: true
    
    Run Code Online (Sandbox Code Playgroud)

    因此,关联变为:

    “用户1-1..0配置文件”,一种关系(因此配置文件可能也可能没有user_id

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

    belongs_to :created_by, class_name: "User", foreign_key: "created_by_id" 
    
    Run Code Online (Sandbox Code Playgroud)
  4. @user.created_by = current_user在Profile#create操作中添加