1
我通過Rails中的關聯有has_many問題。 有型號:has_many通過在Rails中返回多個關聯的對象4
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
所以,我已經創建了一個間隔爲一個用戶,並創建了幾個termins:
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: "[email protected]", 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: "[email protected]", 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: "[email protected]", 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條記錄,因爲有三次相同的用戶。 歡迎任何幫助。 感謝