我通过Rails中的关联来解决has_many问题。 有型号:
class Interval < ActiveRecord::Base
belongs_to :training
has_many :termins
has_many :users, through: :termins
end
class User < ActiveRecord::Base
belongs_to :role
has_many :termins
has_many :intervals, through: :termins
end
class Termin < ActiveRecord::Base
belongs_to :interval
belongs_to :user
end
所以,我为一个用户创建了一个间隔,并创建了几个终端:
Interval.first #=> <Interval id: 6, from: "2014-10-17", to: "2014-11-17", training_id: 1, created_at: "2014-10-16 22:39:38", updated_at: "2014-10-16 22:39:38">
Interval.first.termins
[
#<Termin id: 9, interval_id: 6, user_id: 4, term: "2014-10-16", created_at: "2014-10-16 22:42:15", updated_at: "2014-10-16 22:42:15">,
#<Termin id: 10, interval_id: 6, user_id: 4, term: "2014-10-23", created_at: "2014-10-16 22:43:02", updated_at: "2014-10-16 22:43:02">,
#<Termin id: 11, interval_id: 6, user_id: 4, term: "2014-10-31", created_at: "2014-10-16 22:44:40", updated_at: "2014-10-16 22:44:40">
]
但是,当我把: Interval.first.users
[
#<User id: 4, email: "member@gym.com", encrypted_password: "$2a$10$ChVTiXt2EjKzKYiq4GEvT.d21MuOHydJxCGxDextAYt0...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2014-10-15 22:27:44", updated_at: "2014-10-16 21:21:25", first_name: "Member", last_name: "Member", phone_number: "00000000", date_of_birth: "1989-10-16", sex: "0", role_id: 3>,
#<User id: 4, email: "member@gym.com", encrypted_password: "$2a$10$ChVTiXt2EjKzKYiq4GEvT.d21MuOHydJxCGxDextAYt0...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2014-10-15 22:27:44", updated_at: "2014-10-16 21:21:25", first_name: "Member", last_name: "Member", phone_number: "00000000", date_of_birth: "1989-10-16", sex: "0", role_id: 3>,
#<User id: 4, email: "member@gym.com", encrypted_password: "$2a$10$ChVTiXt2EjKzKYiq4GEvT.d21MuOHydJxCGxDextAYt0...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2014-10-15 22:27:44", updated_at: "2014-10-16 21:21:25", first_name: "Member", last_name: "Member", phone_number: "00000000", date_of_birth: "1989-10-16", sex: "0", role_id: 3>
]
我希望上次查询只能获得1条记录,因为有三次使用相同的用户。 欢迎任何帮助。 感谢
答案 0 :(得分:0)
成功:
has_many :users, -> { uniq }, through: :termins
在Rails 4之前你会使用has_many :users, through: :termins, uniq: true
但现在已经弃用了,上面使用破折号火箭是一种方法。