How Use A Ruby Code Inside The Javascript
Solution 1:
You should take a look at Javascript with Rails, for achive your proposit you will need to create a controller that responds with your js.erb, and this action should be called from a link with data-remote=true
or from ajax.
Solution 2:
You could do something like:
search_engine.html.erb
<%= form_tag(target_path, method::get) do %>
<%= text_field_tag :query, nil, placeholder:"Search by column names...", class: "form-controlsearch-form" %>
<% end %>
live_search.js
$(document).on("change", ".search-form", function() {
return $(this).parents("form").submit();
});
Then in your target model, you could add a search
scope to make it dynamic.
target.rb
classTarget < ActiveRecord::Base
scope :search, -> (query) {
returnif query.blank?;
where("target.column_name1 ILIKE :query or target.column_name2 ILIKE :query or target.column_name3 ILIKE :query", query:"%#{query}%")
}
end
And in your targets_controller.rb
classTargetsController < ApplicationControllerdefsearch_engine@targets = Target.search(params[:query])
endend
Solution 3:
I was able to solve my problem. I discovered that you can't render things in assets and you can't use ruby inside a JavaScript file. I did some workaround and got it done, I included the JavaScript code inside the html.erb file using the <script> JavaScript code </script>
syntax as shown here:
<scripttype="text/javascript">
column =
'<%= form_tag({controller: "people", action: "index"}, method: "get", remote: true) do %>' +
'<% valid_column_names = Person.column_names.reject{|r| r == "created_at" || r == "updated_at" || r == "slug"} %>' +
'<%= j (select_tag :object_columns, options_for_select(valid_column_names)) %>' +
'<%= text_field_tag :search, '', autocomplete: :off %>' +
'<% end %>';
$('button').on('click',function(){
$('button').after(column);
});
</script>
Because the select_tag ruby line generated a sentence with lots of quotation marks, the j used is the same as escape_javascript and it is used to format a sentence so the JavaScript can read it properly.
Post a Comment for "How Use A Ruby Code Inside The Javascript"