开发者

How can I use the 'unless' keyword in a view?

Can anyone tell me if there's a Rail3 replacement for something like this:

<%= unless @page.new_record? || !@page.background_image? %>

bla 

<% end %>

I'm trying to display a checkbox开发者_如何转开发 on a form only when a user edits. Not when they create.


I think the statement is ok, but should not be included in your view. Instead, create a model method, probably named is_editable? or something, that includes this statement. Then get an instance variable in your controller and use that instead.

Logic in views is a very bad idea :)


Your mistake is including the = in the ruby code.

<% unless @page.new_record? || !@page.background_image? %>

  bla 

<% end %>

However, as other users have stated, it is probably better to hide this logic in the model rather than in the view. Additionally it considered a best practice to only use unless if there is only one boolean statement. It starts to get harder and harder to read when you have ors and nots included there.

<% if @page.is_editable %>
  blah
<% end %>

This would be a nicer version, and even better than that (depending on how complicated 'blah' is) would be to hide the whole thing in a helper method.

<%= some_special_checkbox(f) %>

The parameter f would be the form object so that your helper can render the checkbox for the form.


You can write it like this:

<%= "bla" unless @page.new_record? || !@page.background_image? %>

May be you should write separate method with more human-readable name and replace this condition with one method. Try to keep your view as much cleaner as possible

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜