How to display in the view by a given value?

There is a view that displays a list of tasks. Have tasks have a Boolean field done. I want to display only those tasks whose values are done will be true.
Vyuha


 <% @tasks.each do |task| %>

<% end %>
<table>
<thead>
the <tr>
<th></th>
 <th colspan="3"></th>
</tr>
</thead>

<tbody><tr>
 <td><%= link_to task.name edit_task_path(task) %></td>
 <td><%= task.done? %></td>
 <td><%= link_to 'Show', task %></td>
 <td><%= link_to 'Destroy', task, method: :delete, data: {confirm: 'Are you sure?'} %></td>
</tr></tbody>
</table>
<br / >


Controller
def index
 @tasks = Task.all
 #@task = Task.all.sort_by! {|a| a.done?}
 #@task = Task.all.sort {}
 end

Can't figure out how to turn on the field.
June 10th 19 at 16:11
2 answers
June 10th 19 at 16:13
Solution
I understand himself. From the view I had to add <% if task.done %> or <% unless task.done %>
<% @tasks.each do |task| %>
 <% if task.done %>

 <%= link_to task.name edit_task_path(task) %>
 <%= task.done %>
 <%= link_to 'Show', task %>
 <%= link_to 'Destroy', task, method: :delete, data: {confirm: 'Are you sure?'} %>

 <% end %>
 <% end %>


<br / >
Not the best option, you fill the memory with objects that in fact you don't need. Much better to choose what you need immediately at the controller level:

def index
 @tasks = completed_tasks
end

private

 def completed_tasks
 Task.where(done: true)
 end


If you want, you can even declare it as a helper_method completed_tasks class, and pass this method parameters for the additional sort order(*args) from view.

Ideal option for me would be to use enum (task: open/completed), then it would be possible to do: @task = Task.completed - paolo.Okuneva commented on June 10th 19 at 16:16
June 10th 19 at 16:15
It is convenient to make the scope done, not_done, and use them

<% @tasks.done.each do |task| %>
...
<% end %>


To make the scope, should be in app/models/task.rb to register

scope :done, -> { where(done: true) }
scope :not_done, -> { where(done: false) }


The word scope is of course necessary to use not only in the vyuha, can be directly in the controller
@tasks = Task.done
If the controller @tasks defined as Task.done, the view should be:

<% @tasks.each do |task| %>
...
<% end %>


Because when iterating @tasks.done.each you call the scope a second time and recheck done: true has already been selected by this parameter object. - paolo.Okuneva commented on June 10th 19 at 16:18

Find more questions by tags RubyRuby on RailsWeb Development