将记录添加到activerecord数组会更改属性值

时间:2014-08-31 09:03:19

标签: ruby-on-rails ruby activerecord

我有一个包含许多已完成任务的用户模型。此外,我还有订阅,跟随等操作的用户与用户关系。我正在尝试为用户所关注的用户呈现所有用户已完成的任务和已完成的任务。问题是,当我将跟随的用户完成的任务添加到用户完成的任务数组时,user_id列将从跟随的用户ID更改为用户ID。这很奇怪,不知道造成这种情况的原因。对不起,如果我无法解释清楚。

以下是代码:

user.rb

class User < ActiveRecord::Base
  include BCrypt

  before_create :generate_auth_token!

  has_secure_password :validations => false

  has_many :completed_tasks, dependent: :destroy

  has_many :relationships, foreign_key: "follower_id",
                           class_name: "Relationship",
                           dependent: :destroy
  has_many :followed_users, through: :relationships, :source => "followed"

  has_many :reverse_relationships, foreign_key: "followed_id",
                                   class_name:  "Relationship",
                                   dependent:   :destroy
  has_many :followers, through: :reverse_relationships

  def generate_auth_token!
    begin
      self.auth_token = SecureRandom.hex
    end while self.class.exists?(auth_token: auth_token)
  end
end

completed_task.rb

class CompletedTask < ActiveRecord::Base
  belongs_to :user
  validates :user_id, :presence => true
end

completed_tasks_controller.rb这里是@ user.completed_tasks&lt;&lt; user.completed_tasks user_id值变为@ user.id

def index
  if valid_auth_token?
    @completed_tasks = @user.completed_tasks
    @user.followed_users.each do |user|
      @completed_tasks << user.completed_tasks
    end
    render file: "api/v1/completed_tasks/index.json.jbuilder", status: :ok
  else
    head :unauthorized
  end
end

1 个答案:

答案 0 :(得分:1)

您正在改变关联(向其添加对象)并将对象追加到has_many更改外键

您可以通过调用to_a转换为数组:向数组添加对象(而不是关联)不会更改它们

您也可以执行类似

的操作
@completed_tasks = @user.followed_users.inject(@user.completed_tasks) {|result, user| result + user.completed_tasks}

这里的主要区别在于,我没有使用<<(修改数组),而是使用+(返回包含其参数串联的新数组)

相关问题