我正在使用相同的模型构建图片,视频和文字帖子。 对于图像帖子,我有一个图像列,文本是一个正文字段,对于视频一个网址。我对每种类型的帖子都有单独的部分内容。现在我正在循环播放这样的帖子:
<% @posts.each do |post| %>
<% if post.image.present? %>
<%= render 'image_post' %>
<% elsif post.body.present? %>
<%= render 'text_post' %>
<% else %>
<%= render 'video_post' %>
<% end %>
<% end %>
如果我添加更多类型的帖子,它会变得混乱。有更好的方法吗?
另外,假设我想要浏览视频帖子。我是否可以仅使用video_url来播放帖子而不是这样做?
<% @posts.each do |post| %>
<% if post.video_url.present? %>
<%= render 'video_post' %>
<% end %>
<% end %>
答案 0 :(得分:1)
you can add a mothod to you model to return the type of post
def type
return "image" if image.present?
return "text" if body.present?
return "video"
end
In your view
<% @posts.each do |post| %>
<%= render "#{post.type}_post" %>
<% end %>