我怎么能分开我的照片和视频,所以只有一个用户帖子显示



我试图写一个if else语句,以便当用户发布照片时,只显示照片,视频也是如此。现在,如果用户发布视频,视频下方也会显示空白照片。我的代码如下。我知道这和以下几行有关:

<%= image_tag @post.image.url(:medium) %>
<%= video_tag @post.video.url(:medium), controls: true, type: "video/mp4" %>

我只是不知道最好的方法是只显示用户发布的那张。

Post/Show.html

<div class="row">
    <div class="col-md-offset-4 col-med-8">
        <div class="panel panel-default">
        <div class="panel-heading center">
            <%= image_tag @post.image.url(:medium) %>
            <%= video_tag @post.video.url(:medium), controls: true, type: "video/mp4" %>
        </div>
        <div class="panel-body">
        <p><%= @post.description %></p>
        <p><strong><%= @post.user.name if @post.user %></strong></p>
    <% if @post.user == current_user %>
        <%= link_to edit_post_path(@post) do %>
        <span class="glyphicon glyphicon-edit"></span>
        Edit
      <% end %>
    <% end %>
    <%= link_to 'Back', posts_path %>
    </div>
</div>

<%= form_for @post, html: { multipart: true }  do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :image %>
    <%= f.file_field :image %>
  </div>

  <div class="field">
    <%= f.label :video %>
    <%= f.file_field :video %>
  </div></br>

  <div class="field">
    <%= f.label :description %>
    <%= f.text_field :description %>
  </div>
  <div class="actions">
    <%= f.submit class: "btn btn-danger btn-md" %>
  </div>
<% end %>

如果我没理解错的话,你可以试试这个…

<% if @post.respond_to?(:image) %>
  <%= image_tag @post.image.url(:medium) %>
end
<% if @post.respond_to?(:video) %>
  <%= image_tag @post.video.url(:medium), controls: true, type: "video/mp4"  %>
end

基本上是检查特定属性是否存在。你的意思是,如果它在这里,如果它存在,那么显示它。

或者你可以试试这个

<% if @post.image.url != nil %>
   <%= image_tag @post.image.url(:medium) %>
.........(repeat for other attributes)
<% end %>

 <% unless @post.image.url == nil %>
       <%= image_tag @post.image.url(:medium) %>
 <% end %>

查看更多信息

有很多方法可以达到你想要的。这是编程的基本概念之一

相关内容

最新更新