简体   繁体   中英

Ruby code inside Javascript

I have a Ruby form that saves a city id value:

= select_tag 'building[city_id]',
options_for_select(cities.map{|c| [c.name, c.id]})

I'm saving that id using Javascript:

var city_id = $('#building_city_id').val();

My issue is that I also need a Javascript variable for a city name, which I can get using Ruby like this: City.find(@building.city.id).name . I tried this code, but it doesn't wotk:

var city_name = #{City.find(city_id).name};

Where is my mistake? (I'm very new to Ruby)

It doesn't work because the Rails server parses the html.erb view before city_id is defined.

city_id is a Javascript variable defined by the client browser after receiving the view which contains var city_name = #{City.find(city_id).name}; .

You could do an Ajax call that would execute City.find(city_id).name on the server and fill var city_name with the response. Once you know the user has filled an input with some text you can use (ie city_id), you can make a call like so (put this either in the view or in a separate js file):

$.ajax({
  type: "GET",
  url: "/your_ajax_endpoint",
  dataType: 'json',
  data: {'city_id': city_id},
  success: function(data) {
    var city_name = data;
  },
  error: function(data) {
    // Error handling
  }
});

The endpoint in your controller would look like this:

def my_ajax_endpoint
    city_name = City.find(city_id).name
    respond_to do |format|
      format.json { render json: city_name.to_json }
    end
end

You need to pass data using javascript. Here is an example taken from this RailsCast .

products/index.html.erb

<%= content_tag "div", id: "products", data: {products: Product.limit(10)} do %>
  Loading products...
<% end %>

app/assets/javascripts/products.js.coffee

jQuery ->
  alert $('#products').data('products')

Or you can use the gon gem .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM