我有一個用戶模型,有許多完成的任務。此外,我有用戶與用戶之間的訂閱關係,以下等行爲。我正在嘗試呈現所有用戶完成的任務,並完成了用戶所關注用戶的任務。問題是,當我將用戶已完成的任務添加到用戶已完成的任務數組中時,user_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 < < 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
這就是activerecord所做的 - some_user.completed_tasks根據定義是其user_id爲some_user.id的任務集合,因此將任務添加到user.completed_tasks更改user_id – 2014-08-31 09:10:09
@FrederickCheung謝謝!構建一個收集自己的和遵循用戶任務的數組的正確方法是什麼? – samiljin 2014-08-31 09:22:21