rails: accessing a non-instance variable in js.erb - javascript

I have a page that renders multiple forms. Currently, when the user submits any one of these forms, it updates (via ajax) a div on the same page with the content from the form that was just submitted.
I also want to remove() the form element that was just submitted after the ajax post request is completed. However, I need to be able to access that specific form ID within the js.erb file to do so.
Since my page has x number of forms rendered dynamically, I cannot simply access an instance variable in my js.erb.
Page:
<% for peer_review in #peer_reviews %>
<%= render :partial => 'form', :locals => { :peer_review => peer_review } %>
<% end %>
<div id="completed_peer_reviews">
<%= render 'completed_peer_reviews' %>
</div>
The #peer_reviews instance variable contains an array of new PeerReview objects already containing some data.
Form:
<div id="peer_review_form_<%= peer_review.reviewee_id %>">
<%= form_for peer_review, :html => { :method => "post" }, :remote => true do |f| %>
<%= f.error_messages %>
<p>
Peer Review for: <%= User.find(peer_review.reviewee_id).name %><br />
</p>
<p>
<%= f.label :rating %>:
<%= f.select :rating, [1, 2, 3, 4, 5], { :include_blank => 'None' } %>
</p>
<p>
<%= f.label :review %><br />
<%= f.text_area :review %>
</p>
<%= f.hidden_field :user_id, :value => peer_review.user_id %>
<%= f.hidden_field :reviewee_id, :value => peer_review.reviewee_id %>
<%= f.hidden_field :review_period_id, :value => peer_review.review_period_id %>
<p><%= f.submit "Submit" %></p>
<% end %>
</div>
js.erb:
$("#completed_peer_reviews").html("<%= escape_javascript(render('completed_peer_reviews')) %>");
I was hoping to just add another line to the js.erb file that removes the form element that just triggered the execution of the js.erb file like so:
$("#peer_review_form_<%= peer_review.reviewee_id %>").remove();
How should I actually be referencing peer_review.reviewee_id here? Or should I be taking a completely different approach?

This is one of the classic issues of RJS templates.
Quick answer:
If you simply want to solve the problem, you could pass along some temporary id to identify the form. e.g:
# in the index
<% #peer_reviews.each.with_index do |peer_review, i| %>
<%= render :partial => 'form',
:locals => { :peer_review => peer_review, :i => i } %>
<% end %>
# then in the form (note, you don't need to specify POST in a form_for)
<div id="peer_review_form_<%= i %>">
<%= form_for peer_review, :remote => true do |f| %>
<%= hidden_field_tag 'temp_id', i %>
# finally in the create js.erb
$("#peer_review_form_<%= params[:temp_id] %>").remove();
Longer Answer:
That being said, while RJS templates were "the Rails way" for a long time, they've since fallen out of favor.
The more modern method is typically client side JS templates with a JSON API, rather than running server generated JS templates (RJS). This has a lot of advantages, one being that the DOM binding issue you're having right now no longer exists.
This is an example of how you might do this with pure jQuery, but there are many templating options out there.
<script id="peer_review_tmpl" type="text/x-jquery-tmpl">
<div class="completed_peer_review">
<p>${review}</p>
...
</div>
</script>
Then you'd create a handler and bind it to a successful ajax response. This would require that your peer_reviews#create action responded to JSON:
$('form.new_peer_review').bind("ajax:success", function(data) {
// remove the form which triggered the creation
$(this).remove();
// then render the data into a template, and append it to the list
$("#peer_review_tmpl").tmpl(data).appendTo("#completed_peer_reviews");
});

Related

AJAX call being handled but not rendering in rails view

In a rails 4.2 application, a div lists and renders existing cartitems
<div id='yield_cartitem'>
<%= render 'cartitems' %>
</div>
and the same page has forms (one per listed products).
<%= form_for(#cartitem, remote: true, id: 'data-js-cartitem-form', data: {'js-cartitem-form' => true}) do |f| %>
<%= f.hidden_field :product_id, value: product.id %>
<%= f.hidden_field :price, value: product.price %>
<%= f.submit 'Add to cart' %>
<% end %>
The javascript for the class defines via jQuery
$(document).on('turbolinks:load', function() {
$('[data-js-cartitem-form]').on("ajax:success", function(event, data, status, xhr){
var cartitem = $(xhr.responseText).hide();
$('#cartitems').append(cartitem);
cartitem.fadeIn(1000);
document.getElementById('data-js-cartitem-form').reset();
});
$('#cartitems').on("ajax:success", function(event, data, status, xhr){
var cartitem_id = xhr.responseJSON.id;
$('[data-js-cartitem-id=' + cartitem + ']').hide();
});
});
The controller create action runs as by design with the following rendering instruction.
if #cartitem.save
render partial: 'cartitem', locals: {cartitem: #cartitem}
end
_cartitems.html.erb has
<div id=cartitems class='tableize'>
<%= render partial: 'cartitem', collection: #cartitems %>
</div>
while _cartitem.html.erb defines
<div class='row' data-js-cartitem-id=<%= cartitem.id %>>
<%= cartitem.quantity %>
<%= cartitem.um %>
<%= cartitem.product.try(:name) %>
<%= cartitem.price %>
</div>
_cartitem.js.erb calls $("div#yield_cartitem").html('< %=j (render 'cartitem') %>');
The XHR response payload is returning $("div#yield_cartitem").html('< %=j (render 'cartitem') %>'); but the div is not refreshing with the newly created cartitem.
Where has this gone wrong?
update
Trying to simplify matters by changing the _cartitems.js.erb to an alert:
alert("<%= cartitem.quantity %> <%=j cartitem.um %> <%=j cartitem.product.try(:name) %> <%= number_to_currency(cartitem.price) %> Added")
The alert does effectively render.
alert("1.0 kg Prod 1,89 € Added")
I may be wrong but I noticed that in controller you are passing locals to cartitem html partial but not in js.erb file. So do that in cartitem.js.erb file:
$("div#yield_cartitem").html('< %=j (render 'cartitem', cartitem: cartitem) %>');
it's really hard to debug js.erb files but it's possible. Try to use gem pry to see context and variables inside the partial.
$("div#yield_cartitem").html('<%= binding.pry; j(render 'cartitem', cartitem: cartitem) %>');
$("div#yield_cartitem").html('<%=j (render 'cartitem') %>') this will replace the contents of #yield_cartitem
instead use $('#cartitems').append('<%= j render('cartitem', cartitem: #cartitem) %>')
and update this function
$('[data-js-cartitem-form]').on("ajax:success", function(event, data, status, xhr){
// var cartitem = $(xhr.responseText).hide();
// $('#cartitems').append(cartitem);
// cartitem.fadeIn(1000);
document.getElementById('data-js-cartitem-form').reset();
});
Additionally rename _cartitem.js.erb to create.js.erb then create will render it automatically

Rails reCAPTCHA with callback

I am trying to integrate a recaptcha into my website and I wanted to add some client side validation.
I chose to use a gem to include the recaptcha tags, but I wanted to trigger a function once the recaptcha is checked.
Looked through some google sites and found that a data-callback attribute with its value set to function name is all I need.
I used recaptcha_tags helper from the gem to set it up and then a jquery method to add this data-callback attribute as I have not seed an option to do this inside the gem.
$('.g-recaptcha').attr("data-callback", "myFunctionName");
After clicking the recaptcha the function is not called. Why?
I asume you have a form like this
app/views/contacts/contact.html.erb
<%= form_for #contact do |f| %>
<%= f.text_field :nombre, :placeholder => I18n.t("contacto_formulario_nombre"),:required => true %>
<%= f.text_field :apellido :placeholder => I18n.t("contacto_formulario_apellidos"), :required => true %>
<%= f.text_field :email, :placeholder => I18n.t("contacto_formulario_email"), :required => true %>
/** (....other tags ....) **/
<%= recaptcha_tags :display => 'clean' %>
<%= f.button I18n.t("contacto_formulario_continuar"), type: "submit" %>
<% end %>
app/assets/javascripts/contact.js
$(function() {
$('.g-recaptcha').attr("data-callback", "recaptcha");
})
function recaptcha()
{
console.log("captcha pulsado!");
/** the actions you want, i.e. activate submit button **/
}
The magic ocurrs in the attribute "data-callback"
Hope it helps.
Marino

Dynamically add fields in rails with out nested attributes

I am in the early stages of creating an app, and am just putting some basic code in place. Here is the current code...
app/views/cards/front.html.erb
<%= form_for(front_of_card_path) do |f| %>
<%= f.fields_for :competency_templates do |builder| %>
<%= render 'add_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add New Tag", f, :skill %>
<% end %>
routes
controller :cards do
get '/front', action: 'front', as: 'front_of_card'
post '/save', action: 'create', as: 'save_card'
get '/my_contact_info', action: 'back', as: 'back_of_card'
put '/save', action: 'update', as: 'save_card'
get '/my_card', action: 'show', as: 'card'
end
controller
def create
#skill= Skill.new(params[:skill])
#tag = Tag.new(params[:tag])
#tag.save
#skill.tag_id = #tag.id
#skill.save
redirect_to front_of_card_path, notice: 'Skill was successfully created.'
#get user/session
#save skills & tags
end
cards.js.coffee
jQuery ->
$('form').on 'click', '.remove_fields', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('fieldset').hide()
event.preventDefault()
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
app_helper
module ApplicationHelper
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
end
So right now this code gives me two text fields. One for the a tag name and another for a tag weight, and the controller inserts everything in the DB. I would like use some javascript to dynamically add as many of these tag/weight fields as I like. Everything I've found seems to focus on nested attributes. Any ideas appreciated.
Update
Added more code to flesh this out. The issue I am having is the 3rd variable I am passing in on this line...
<%= link_to_add_fields "Add New Tag", f, :skill %>
It does not like ':skill', but I am not sure what I should be passing here.
So here is what I came up with...here are my two models...
class Skill < ActiveRecord::Base
belongs_to :tag
attr_accessible :tag_id, :weight
end
class Tag < ActiveRecord::Base
has_many :skills
attr_accessible :name
end
I'm calling a partial from app/views/skills/_form.html.erb and using a js tag to add new fields. Also note that I am re-rendering the partial, then hiding it in the last div tag.
<div id="skillSet">
<%= render partial: "skills_form" %>
</div>
Add New Tag
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<div class="hide" id="new_skills_form">
<%= render partial: "skills_form", locals: {skill: false} %>
</div>
The partial is pretty simple. All I am doing here is storing the values in an array...
<div class="skillsForm">
<%= label_tag 'tag' %>
<%= text_field_tag 'tags[]' %>
<%= label_tag 'weight' %>
<%= text_field_tag 'weights[]' %>
</div>
...here is the javascript...real straight forward, just say when #addNewTag is clicked, appeand #new_skills_form to #skillSet
$(document).ready(function(){
$("#addNewTag").click(function(){
$("#skillSet").append($("#new_skills_form").html());
});
});
...and finally the controller action decontructs the arrays, and saves them...
def create
#skill = Skill.new(params[:skill])
tags = params[:tags]
weights = params[:weights]
tags.each_with_index do |tag, index|
tag = Tag.create :name => tag
Skill.create :tag_id => tag.id, :weight => weights[index]
end
end

AJAX Fave Button Not Working Rails

I'm trying to allow users to favorite posts and then it show them sort of of interaction through AJAX, but it's not working.
The error I'm getting in the console is:
ActionView::Template::Error (undefined local variable or method `post_item' for #<#<Class:0x007fecb2a3d5f8>:0x007fecb2a357e0>):
The button is being rendered through a partial:
<%= render "shared/fave_form", post_item: post_item %>
Here's the code for the button (shared/_fave_form.html.erb):
<% if current_user.voted_on?(Post.find(post_item)) %>
<%= link_to "unlike", vote_against_post_path(post_item.id), :remote => true, :method => :post, :class => "btn") %>
<% else %>
<%= link_to "like", vote_up_post_path(post_item.id), :remote => true, :method => :post, :class => "btn") %>
<% end %>
Here's the toggle.js.erb file:
$("#fave").html("<%= escape_javascript render('fave_form') %>");
When you render the partial using toggle.js.erb it is not getting locals value post_item, you have to provide it in also.So, your js code should be something like following
$("#fave").html("<%= escape_javascript(render :partial=>"fave_form", locals: {post_item: post_item}).html_safe %>);
I guess you are using some ajax call and then your toggle.js.erb so in your toggle action you must specify value to post_item, lets make it instance variable #post_item so that we can use it in toggle.js.erb.
$("#fave").html("<%= escape_javascript(render :partial=>"fave_form", locals: {post_item: #post_item}).html_safe %>);
The partial is using a local variable, so pass post_item as a local:
<%= render :partial => "shared/fave_form", :locals => {post_item: post_item} %>

Routing error that appears to have something to do with partials and/or forms

In a Rails 3 application, I have a "table" partial that contains a data entry form table, plus a separate smaller form (mostly hidden fields) below it to clear the table data. I have a third form underneath the partial to add a new column to the table contained in the partial. The page loads fine. The small form to clear the table data works, and refreshes the partial as it is supposed to. BUT, When I submit the add-new-column form, I get this routing error:
ActionView::Template::Error (No route matches {:controller=>"outcome_results", :action=>"clear_table"}):
70: </table>
71: <%= submit_tag "Save" %>
72: <% end %>
73: <%= form_tag url_for(:controller => 'outcome_results', :action => 'clear_table'), :id => "clear_data_table_link", :remote => true do %>
74: <%= hidden_field_tag "subgroup_id", subgroup_id %>
75: <%= hidden_field_tag "outcome_id", #selected_outcome_object.id %>
76: <%= hidden_field_tag "timepoint_id", timepoint_id %>
app/views/outcome_results/_table.html.erb:73:in `_app_views_outcome_results__table_html_erb__204353865_18893424_435027370'
app/controllers/outcome_columns_controller.rb:36:in `block (3 levels) in create'
app/controllers/outcome_columns_controller.rb:35:in `block (2 levels) in create'
app/controllers/outcome_columns_controller.rb:33:in `create'
Line 72 is the end tag of the first (table/data entry) form.
Line 73 is the form tag for my clear-table-data form which works fine on its own - no routing errors there.
My routes.rb is crazy long but contains this line:
match 'projects/:project_id/studies/:study_id/clear_table' => 'outcome_results#clear_table'
The add-new-column form looks like this:
<div id="outcome_column_validation_message"></div>
<%= form_for #outcome_column, :action => :create, :remote => true, :id=>"outcome_columns_form" do |f| %>
<%= hidden_field_tag "outcome_id", !#selected_outcome_object.nil? ? #selected_outcome_object.id : nil %>
<%= hidden_field_tag "subgroup_id", !#selected_timepoint.nil? ? #selected_timepoint : 0 %>
<%= hidden_field_tag "timepoint_id", !#selected_subgroup.nil? ? #selected_subgroup : 0 %>
<div class="field">
Custom Column Title: <%= f.text_field :name %> Description: <%= f.text_field :description %> <%= f.submit "Add Custom Column" %>
<% end %>
and the format section of the "create" action in the "outcome_column" controller looks like this:
respond_to do |format|
format.js {
render :update do |page|
page.replace_html 'outcome_results_table', :partial => 'outcome_results/table'
page['outcome_columns_form'].reset
page.replace_html 'outcome_column_validation_message', ""
end
}
end
I can post more code if it would help... anyone have any ideas about this routing error?
Thanks in advance.
The route would take two arguments: a project_id and a study_id. This is not matching the route because you have not passed through these two parameters to the url_for in your form_tag.

Categories