Trying to put ruby code in an if then statement in .rhtml

This code, in my view(.rhtml file) causes the error which I'll post below.

-----The Code----- <%= if (@announcement.image == nil) then

<a href = "<%= url_for_file_column('announcement', 'image') %>" >Download</a>

end %>

----The Error---- compile error ./script/../config/../app/views/committee/audit_archive.rhtml:118: syntax error            <a href = "<%= url_for_file_column('announcement', 'image') ).to_s); _erbout.concat "\" >Download</a>\n"

Any ideas on the cause of this? Thanks for any and all help!

Use <% if... Not <%= if...

<% if condition %>

<% else %>

<% end %>

Inside each part use normal ERB tags and HTML.

No luck!

The problem seems to be with the <a href part of the code.

Use <% if... Not <%= if...

> This code, in my view(.rhtml file) causes the error > which I'll post below. > > -----The Code----- > <%= if (@announcement.image == nil) then > > <a href = "<%= url_for_file_column('announcement', > 'image') %>" >Download</a> > > end %> > > ----The Error---- > compile error >

./script/../config/../app/views/committee/audit_archive.rhtml:118:

<%= if (@announcement.image == nil) then

<% if @announcement.image.nil? %> ... <% end %>

Ruby ain't PHP :slight_smile:

Both work, but for the sake of RUBY I probably should write it like this. Thanks.

--- Sven Schwyn <rails-mailing-list@andreas-s.net> wrote:

Hi --

This code, in my view(.rhtml file) causes the error which I'll post below.

-----The Code----- <%= if (@announcement.image == nil) then

<a href = "<%= url_for_file_column('announcement', 'image') %>" >Download</a>

end %>

See other replies for the right technique. One comment I'll make is to note in particular that ERb delimiters are not reentrant. To insert a string conditionally, you could do something like this:

   <%= "<a href=#{url_for_file_column('announcement','image)}" if        @announcement.image.nil %>

and if the "if" fails, the whole expression will be nil, which will be interpolated as an empty string. It's not generally the best way to do it, though; the separate <% if %> ... <% end %> things are better, because they're easier to parse visually and also they don't interpolate anything, not even an empty string. Also, the if-modifier is fragile; it won't be happy if you break the line before it. I would mainly use the above technique for short things like:

   <%= @user.middle_name %>

where I can go ahead and do the interpolation without really caring whether the value is nil or not (or "" for that matter). Except what I'd really do is write a User#whole_name method :slight_smile: But you see the point.

David

Try this...

<% if @announcement.image.nil? %> <%= link_to 'Download', url_for_file_column('announcement', 'image') %> <% end %>

This did it! Thanks for responding everyone.

--- Jeremy Weiskotten