PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 18, 2022

[FIXED] How to render different versions of the same file?

 May 18, 2022     controller, if-statement, partial, ruby, ruby-on-rails     No comments   

Issue

For example I have this file:

_goal.html.erb

<table>
  <tr>
    <%= goal.name %>
    <span class="label label-info"><%= goal.deadline.strftime("%d %b %Y") %></span>
  </tr>
</table>

It is being rendered from the home page:

 <h1><b>Goals</b></h1>
   <%= render @unaccomplished_goals %>
   <%= render @accomplished_goals %>
<% end %> 

How can we wrap an accomplished goal with <span class="label label-info-success"> but if it is an unaccomplished goal keep it <span class="label label-info">?

In the controller:

@accomplished_goals = current_user.goals.accomplished
@unaccomplished_goals = current_user.goals.unaccomplished

Here was my latest attempt, which just made them all -info:

<% if @unaccomplished_goals == true %>
  <span class="label label-info"><%= goal.deadline.strftime("%d %b %Y") %></span>
<% else @accomplished_goals == true %>
  <span class="label label-warning"><%= goal.deadline.strftime("%d %b %Y") %></span>
<% end %>

Maybe you'll have more luck :)

Thank you so much.


Solution

Create a helper method that returns the correct classes for the goal's status. In application_helper.rb:

def deadline_label_class(goal)
  if goal.accomplished?
    'label label-info'
  else
    'label label-warning'
  end
end

This assumes that Goal has an instance method called accomplished? which returns true/false. You may have to write that method if it doesn't exist or use some other criteria.

Then use the helper in the _goal.html.erb template:

<table>
  <tr>
    <%= goal.name %>
    <span class="<%= deadline_label_class(goal) %>">
      <%= goal.deadline.strftime("%d %b %Y") %>
    </span>
  </tr>
</table>


Answered By - infused
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing