Last active
August 29, 2015 14:24
-
-
Save chiastolite/4b95d88811b6355ae540 to your computer and use it in GitHub Desktop.
こういうhas_oneの使い方ってありなんだろうか?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Entry < ActiveRecord:Base | |
has_many :messages | |
has_one :latest_message, -> { merge(Message.latest) }, class_name: 'Message' | |
end | |
class Message < ActiveRecord:Base | |
scope :latest, -> { order(id: :desc) } | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
irb(main):003:0> @entry = entry.first | |
Entry Load (0.2ms) SELECT "entries".* FROM "entries" ORDER BY "entries"."id" ASC LIMIT 1 | |
irb(main):003:0> @entry.latest_message | |
Message Load (0.2ms) SELECT "messages".* FROM "messages" WHERE "messages"."entry_id" = ? ORDER BY "messages"."id" DESC LIMIT 1 [["entry_id", 1]] | |
=> #<Message id: 10, body: "Message9", entry_id: 1, created_at: "2015-06-30 16:06:47", updated_at: "2015-06-30 16:06:47"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
よいらしい
編集しないからreadonlyしたほうがいいとのこと