简体   繁体   中英

How do I prevent the empty instance from appearing in the view?

I have topics_controller.rb that creates a new @reply instance variable for the inline form in the show page.

def show
  @topic = Topic.find(params[:id])
  @replies = @topic.replies
  @reply = @topic.replies.new
end

Now when I loop through @replies to display and style existing replies, An empty div appears because of the new instance of the reply in controller.

<% @replies.each do |reply| %>
    <div class="reply span8">
      <%= reply.body %>
    </div>
<% end %>

How do I tackle this and hide the @topic.replies.new instance from showing up?

Try this:

<% @replies.each do |reply| %>
  <% next unless reply.body %>
    <div class="reply span8">
      <%= reply.body %>
    </div>
<% end %>

You can easily create new instance directly:

def show
  @topic = Topic.find(params[:id])
  @replies = @topic.replies
  @reply = Reply.new(topic_id: params[:id])
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM