Tutorial :block always returns true



Question:

Will always return true and erase the entire array

<% users.delete_if do |user| %>    <% false %>  <% end %>  

On the other hand

<%  users.delete_if do |user|    false  end  %>  

works and does not delete the array.

Can i somehow use the delete_if statement in my view and still be able to insert html?

Thanks


Solution:1

You shouldn't be modifying data at all in your views -- do this in your controller or model instead. Use views only to reflect the current state of your database, not change it.

If you then use the second version of your code in either of those places, this problem will disappear.


Solution:2

Ignoring the side-effect-in-a-view aspect, here is why the block "returns" a value: there is a generated print statement as part of the ERB template generated code between the "%>" and the "<% end". Any value left behind by this generated code will be used as the final statement / expression in the block, and thus its value.


Solution:3

I think, and I would have to test it if you use "yield" in the first form, it will work.

<% users.delete_if do |user| %>    <% yield false %>  <% end %>  

But, as the first poster says, you shouldn't change data from a view.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »