Skip to content

Instantly share code, notes, and snippets.

@chiastolite
Last active August 29, 2015 14:24
Show Gist options
  • Save chiastolite/4b95d88811b6355ae540 to your computer and use it in GitHub Desktop.
Save chiastolite/4b95d88811b6355ae540 to your computer and use it in GitHub Desktop.
こういうhas_oneの使い方ってありなんだろうか?
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
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">
@chiastolite
Copy link
Author

よいらしい
編集しないからreadonlyしたほうがいいとのこと

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment