开发者

If/Unless Conditionals in form_for / ERB

I have a form which accepts URL params (to support a bookmarklet) which looks and works like this:

<%= f.url_field :url, :value => params[:u] %>

However, when re-rendered (in case of a validation error, for instance, the content is stripped out.

What I'd like to do is put something like this, so that :value => is only rendered if there are params in the first place:

<%= f.url_field :url, :value => params[:u] if params[:u] %>

Of course this doesn't even render the开发者_开发问答 field and is wrong.

How do I add if/unless conditionals into an ERB block? Endless searching hasn't turned up much, but I'm probably searching for the wrong thing.


Try This...

<%= f.url_field :url, :value => (params[:u] if params[:u]) %>


(I misread your question. Probably not the answer...)

Try this in your view

<%= f.url_field @url %>

and in your controller put

@url = Url.new(params[:u])

That way, you'll have a form with the fields filled unless params is nil.


For a one-liner, try:

<%= f.url_field :url, :value => (params[:u] || 'any_other_value_or_just_nil') %>


Farnoy's answer was very close, but more specifically it was:

<%= f.url_field :url, :value => (params[:u] || @resource[:url]) %>

As @resource was the model object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜