2

基本的に、私は ActiveRecord リレーションの典型的なグループを取り上げて、それを単一のより単純なリレーションのように見せたいと考えています。

投稿に多くのコメントがあり、コメントにはユーザーがいる典型的な , があるとしますPostCommentUser

ここで、次のデータをビューに取り込みたいとします。(必要なすべてのデータを単一の Arel ステートメントで読み取ることができると仮定します)。

post.title
post.tag.name
post.comments.last
post.comments.last.user.full_name

次のメソッドを使用して、PostSummary という新しいオブジェクトを介してそれらにアクセスしたいと思います。

post_summary.title
post_summary.tag_name
post_summary.last_comment
post_summary.last_comment_user

これまでのところ、それほどトリッキーではありません。これは OpenStruct といくつかのマッピングを介して実行できますが、PostSummary を読み取り専用の ActiveRecord::Relation オブジェクトにして、次のことができるようにしたいと考えています。

PostSummary.first.attributes #=> [title, tag_name, last_comment, last_comment_user]
PostSummary.count #=> 42
...

これは多くの作業で可能であると確信していますが、これを行うためのセットアップはすでにありますか?

4

1 に答える 1

2

Seems kinda messy to do what you're suggesting. I'd recommend dropping these methods in a decorator. Decorators are often used to hold information and methods that are relevant for the view to avoid bloat on your models.

For a good decorator library see Draper.

于 2013-09-26T23:09:32.570 に答える