RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

Rails 2.3.8 - select box causing parse error when box contains more than one option

The app in question utilizes jQuery to do ajax requests in order to populate dependent select boxes. My controller action responds_to :js, and in the .js.erb file I have:

str += '<%= f.select field.name, list, {}, { :class => "list", :multiple => "multiple", :style => "size:8; width:100px;" } %>';

"list" is populated like so:

str += '<% list = @validation_model.lookup([field], @lookup) %>';

I am .append()'ing this to a div. at the end of the .js.erb template file. However, when "list" contains more than one value, the parsing of the template fails. If it is empty, or contains only one value, parsing is successful.

Is this a bug I am running into, or am I doing something wrong? Please note this is appearing as a parse error rather than a runtime error, so I have been unable to determine exactly what the problem is in either Firebug or Safari Dev.

UPDATE: Here is the full code of the .js.erb file. I have replaced the "list" variable with inline logic to retrieve an array.

str = '<% fields_for :mapapps do |f| %>';
<% for tf in @tag.tag_fields.find(:all, :order => :sequence) %>
    <% field = tf.parentfield %>
    <% if [email protected]?(field) %>
        $("#<%= field.name %>").remove();
    <% else %>
        <% next %>
    <% end %>
    str += '<div id="<%= field.name %>" class="floater">';
    str += '<label for="mapapps_<%= field.name %>"><%= field.label %></label>';
    str += '<%= f.select field.name, @validation_model.lookup([field], @lookup), {}, { :class => "list", :multiple => "multiple", :style => "size:8; width:100px;" } %>';
    str += '</div>';
<% end %>
str += '<% end %>'
$("#mfrsdiv").append(str);

Upvotes: 0

Views: 483

Answers (2)

RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

I got the code working. All I needed to do was to put "escape_javascript" around the call to f.select.

str += '<%= escape_javascript(f.select field.name, @validation_model.lookup([field], @lookup), {}, { :class => "list", :multiple => "multiple", :style => "size:8; width:100px;" }) %>';

It should be noted that the code in my question above will still fail for the reasons mentioned rubyprince, but the rendering issue itself is solved by the escape_javascript.

Upvotes: 0

rubyprince
rubyprince

Reputation: 17793

I think you are under the impression that eruby items can be appended to the string and will be calculated in the view. Actually the eruby items are calculated in .js.erb file itself and then appended to the string. In your code, f must be the form variable from the view..it will not have value in the .js.erb file. If you really want to add this select to the form, you should be thinking of a partial and using Ajax.

Upvotes: 1

Related Questions