Ruby on rails 将记录添加到activerecord数组会更改属性值
我有一个用户模型,它有许多已完成的任务。此外,我还有用户对用户的关系,用于订阅、跟踪等操作。我正在尝试呈现所有用户已完成的任务,以及用户正在跟踪的用户已完成的任务。问题是,当我将followed users completed tasks添加到users completed task数组中时,user_id列从followed users id更改为user id。这很奇怪,我不知道是什么原因造成的。对不起,如果我不能解释清楚的话 以下是代码: user.rbRuby on rails 将记录添加到activerecord数组会更改属性值,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我有一个用户模型,它有许多已完成的任务。此外,我还有用户对用户的关系,用于订阅、跟踪等操作。我正在尝试呈现所有用户已完成的任务,以及用户正在跟踪的用户已完成的任务。问题是,当我将followed users completed tasks添加到users completed task数组中时,user_id列从followed users id更改为user id。这很奇怪,我不知道是什么原因造成的。对不起,如果我不能解释清楚的话 以下是代码: user.rb class User < A
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
class用户false
已完成多个任务,依赖::销毁
有很多:关系,外键:“追随者id”,
类名:“关系”,
依赖::销毁
通过::relationships,:source=>“跟踪”跟踪了\u多个用户
有很多:反向关系,外键:“跟随id”,
类名:“关系”,
依赖::销毁
拥有多个:追随者,通过::反向关系
def生成授权令牌!
开始
self.auth_token=SecureRandom.hex
self.class.exists时结束?(身份验证令牌:身份验证令牌)
结束
结束
已完成_task.rb
class CompletedTask < ActiveRecord::Base
belongs_to :user
validates :user_id, :presence => true
end
class CompletedTasktrue
结束
@user.completed_tasks中的completed_tasks_controller.rb您正在修改关联(将对象附加到关联中),并且将对象附加到
会更改外键
您可以通过调用转换为数组:将对象添加到数组(与关联相反)不会改变它们
你也可以这样做
@completed_tasks = @user.followed_users.inject(@user.completed_tasks) {|result, user| result + user.completed_tasks}
这里的主要区别在于,activerecord没有使用,而是定义了用户id为某个用户id的任务集,因此将任务添加到用户id中会更改用户_id@FrederickCheung非常感谢。构建一个收集自己和后续用户任务的阵列的正确方法是什么?
@completed_tasks = @user.followed_users.inject(@user.completed_tasks) {|result, user| result + user.completed_tasks}