开发者

Rails - Conditional Form Elements?

I have the following in a form:

<%= f.hidden_field (:project_id, :value => @project.id) %>

This form partial sometimes contains a @project. Sometimes it does not. This is the nature of the app.

But I want to use one partial because it's a big form. Problem here is if it does not contain @project, the page ERRORS....

How can I do the following:

  • Only render the hidden field if @project is defined
  • 开发者_如何学运维If @project is not defined, give the field a value of =""

Thank you!


You seem to be asking a couple different things. If you want to conditionally render the field, meaning the field doesn't appear at all if @project is undefined, do this:

<%= f.hidden_field(:project_id, :value => @project.id) if @project %>

If you want the value to be blank when there is no project, you can trim down the previous answer's conditional a little:

<%= f.hidden_field (:project_id, :value => @project ? @project.id : '') %>

There's no need to check that @project is both defined and not nil, since it's a global variable and calling it directly won't trigger a "no method" error.


<%= f.hidden_field (:project_id, :value => defined?(@project) && @project ? @project.id : '') %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜