私なら、ツイートのモデルのdailymodel,foodmodel,trainingmodelの上位にtweetモデルでも作って、投稿者の情報をそこに集約します。
その上で、Viewのほうでは、render: :partialをうまいこと使って、出来るだけDRYに書くようにします。
Ruby
1class Author < ActiveRecord::Base
2 has_many :tweets
3 has_many :follower_relations
4 has_many :followers through: :follower_relations, source: :author_id
5
6 def visible_authors
7 authors = self.followers
8 authros << self
9 return authors
10 end
11end
12
13class Tweet < ActiveRecrd::Base
14 belongs_to :author
15 has_one :daily
16 has_one :food
17 has_one :training
18 validate :any_content_must_exist
19
20 def any_content_must_exist
21 unless self.daily || self.food || self.training
22 self.errors.add(:base, "daily, food, trainingのいずれかが無ければなりません")
23 end
24 end
25 # tweetに入れられるコンテンツは一つだけ
26 def daily=(dailymodel)
27 self.food = nil
28 self.training = nil
29 end
30 # food,trainingも同様にする
31end
32
33class TweetController < ApplicationController
34 def index
35 tweet_table = Tweet.arel_table
36 @tweets = tweet_table.includes([:author, :daily, :food, :training]).where(tweet_table[:author_id].in(@current_author.visible_authors.map{|a|a.id}).order(tweet_table[:tweet_at].desc).all
37 end
38end
html
1<!-- index.html.erb -->
2<% @tweets.each do |tweet| %>
3 <%= render partial: 'author_column', locals: {author: tweet.author} %>
4 <!-- tweetで共通の表示項目をここに表示 -->
5 <% if tweet.daily %>
6 <%= render partial: 'daily', locals: {daily: tweet.daily} %>
7 <% elsif tweet.food %>
8 <%= render partial: 'food', locals: {daily: tweet.food} %>
9 <% else %>
10 <%= render partial: 'training', locals: {daily: tweet.training} %>
11 <% end %>
12<% end %>
partialのテンプレートは省略
partialで表示するテンプレートは全部共通なので、Viewをたくさん書かなくてもいいです。
結構適当に書いたので動かないですが、雰囲気だけでも。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/08/07 12:03