Using jQuery to update multiple objects - javascript

I have a profile page where I render all of the user's lists using a partial:
users/show.html.erb
<%= render #lists %>
For each list I show how many wishes are associated:
lists/_list.html.erb
<p class="muted" id="wishes_count"><%= pluralize(list.wishes.count, "wish") %></p>
I'm using drag and drop to allow the user to move wishes from one list to another using jQuery sortable.
Right now, I'm using the following code:
wishes.js.erb
$(document).ready(function(){
$('.user_list_wishes').sortable({
connectWith: ".user_list_wishes",
items: ".user_list_wish",
placeholder: "sortable_placeholder",
update: function(e, ui)
{
if (this === ui.item.parent()[0])
{
item_id = ui.item.data('item-id');
list_id = $(this).data('list-id');
position = ui.item.index();
$.ajax({
type: 'POST',
url: $(this).data('update-url'),
dataType: 'json',
data: { id: item_id, wish: { row_order_position: position, list_id: list_id } }
}),
$("#wishes_count").html('<%= pluralize(list.wishes.count, "wish") %>')
}
}
})
})
This line of code:
$("#wishes_count").html('<%= pluralize(list.wishes.count, "wish") %>')
makes my application throw a NoMethodError undefined method 'wishes' for nil:NilClass
I believe it has something to do with how I render lists and reference them individually in my javascript?
Any suggestions on how to solve this problem is much appreciated!

You must handle the scenario where list is null using the following condition:
$("#wishes_count").html('<%= pluralize(list ? list.wishes.count : 0, "wish") %>')

I think the problem could be in your render call - according to the documentation:
If you have an instance of a model to render into a partial, you can use a shorthand syntax:
<%= render #customer %>
Assuming that the #customer instance variable contains an instance of the Customer model, this will use _customer.html.erb to render it and will pass the local variable customer into the partial which will refer to the #customer instance variable in the parent view.
So check that this is the case - do you have a partial called _lists.html.erb and a parent variable called list?

Related

Re-render a page using jquery

In react, I could easily re-render a view by passing results from controller. I wish not to use React at this stage and was wondering if it's possible with JQuery?
I have few objects on page, and when clicked, I should see its content. Click the other object, I see its content etc. Sense? I was inspired by this dribbble.
I may not be doing this the right way but this is what I have:
Controller:
def index
selected_contract = params[:selected_contract] || current_user.contracts.last.id
#contracts = current_user.contracts.order(created_at: :desc).all
#selected_contract = current_user.contracts.find_by(id: selected_contract)
end
View:
<% #contracts.each do |contract| %>
<button class="ui button test" id="<%=contract.id%>"><%=contract.name%></button>
<% end %>
......................................
When clicked, show its content
....................................
<%= #selected_contract.name %>
JS:
$( ".ui.button.test" ).click(function(e) {
let { id } = this
console.log(id)
$.ajax({
url: `/url/${id}`,
type: 'POST',
success: function(result) {
//$('#listview').redraw()
console.log('success')
}
});
});
Routes are set properly so I get the params in the controller just fine. Is there a re-render a view, just like rerender a prop in React for jquery? Am I doing this the correct way?
If you are using jquery listview this should work.
$( "#listview" ).listview( "refresh" );
Reference
https://api.jquerymobile.com/listview/#method-refresh
or since its rails you can reload or render the partial view in your server side as well.

calling .val() on date_select element returning undefined?

I'm trying to obtain the selected date from a date_select:
<%= form_for(#newevent) do |f| %>
<%= f.date_select :day, { id: "date-select"} %>
<button id="check-button" type="button">Check</button>
<% end %>
using JQuery/Javascript:
$(document).on('click', "#check-button", function(){
var selectedDate = $("#date-select").val();
alert(selectedDate);
var checkList = []; //creates array to store customer ids
$("#check-list li input").each(function(){ //for each listed colleague...
if( $(this).is(":checked")){ //if check-box is ticked
checkList.push($(this).val()); //add id to list
}
});
$.ajax({
url: '/events/check',
data: {checkList: checkList , selected_date: selectedDate },
method: "POST"
}
);
});
for reference here is where :day is defined in my migration file:
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.timestamps
t.references :calendar, foreign_key: true
...
t.date :day
...
end
However, on alert the returned value is "undefined". Why is this happening? I would like it to return the a value in the form YYYY-MM-DD. Apologies if this is obvious, but I am new to programming and can't seem to fix this one myself
Date_select, according to the rails api "Returns a set of select tags (one for year, month, and day)". Your javascript is going to have to deal with three separate selects and construct a date from them. Look at your generated HTML to get the id's.

Update attribute with ajax call rails

I appreciate that there may be many answers out there but if there are i cant quite interpret them to suit my needs..I am looking to update a records attribute in my model using ajax.
In my case the attribute selected: true
In my scenario i am clicking on an element and looking to update that elements record in the model
<ul class="components">
<% #component.each do |c| %>
<li id="<%= c.component_name %>" data-id="<%= c.id %>" data-remote="true"><%= c.component_name %></li>
<% end %>
</ul>
jQuery
$('#Literacy, #Numeracy').on('click', function(){
var component_name = $(this).text();
var component_id = $(this).data('id');
data_send = { id: component_id }
$.ajax({
method: 'put',
url: '/components/selected_component',
data: data_send,
success: function(data) {
console.log(data)
}
});
});
Controller
def selected_component
#component = Component.find(params[:id])
#component.update_attributes(selected: true)
end
Maybe im looking at this incorrectly but how can i get the id via the click event (stored as component_id) into my selected_component method
Im missing a few bits here but struggling with what today
At the moment I am getting an error
Missing template components/selected_component
but i dont want to render that page after successful update, I just want to stay on the same page
EDIT
to solve my issue i just had to add this to my format.js
{ render nothing: true }
A missing template error corresponds to not having a view that knows what to do when it gets a JavaScript request.
In your views/components/, just make an selected_components.js.erb file and that should clear the error you're getting.

Rails 4 / Ruby 2: Local variable (FormBuilder) for partial is lost through dynamic update

I have this form that renders a partial for selecting a person's task.
new.html.slim:
= form_for(#person) do |f|
= f.text_field :name
= f.fields_for :assignment do |a|
= a.collection_select :project_id, Project.order(:name), :id, :name
div id="task_list"
= render 'shared/_task_select', a: a
= f.submit 'Save'
shared/_task_select.html.slim:
= a.collection_select :task_id, #tasks, :id, :name
Changing the project triggers a javascript that runs a "create_tasklist"-method in the PersonsController.
new.js:
$(document).ready(function() {
$('#person_assignment_attributes_project_id').change(function() {
var selection = $('#person_assignment_attributes_project_id').val();
$.ajax({
url: "/create_tasklist",
data: {
project_id : selection
},
dataType: "script"
});
});
});
The "create_tasklist"-method triggers a javascript that updates the partial:
create_tasklist.js.erb:
$("#task_list").html("<%= escape_javascript(render 'shared/task_list', a: a) %>");
Now this raises the error:
undefined local variable or method `a' for #<#<Class:0x42cd770>:0x4213ef0>
The same form works well when editing existing persons - until changing the project. Thus, FormBuilder "a" loses its definition through the javascript actions. I have to use a partial here because I want to do more stuff with it in a later stage. Any ideas how to get that variable to keep its defintion?
Edit 1:
I already tried adding this below the third line of new.html.slim:
javascript:
var a = "#{a}";
and then adding: a: a in the "data" declaration of new.js.
Edit 2:
With this the FormBuilder seems to pass through until the "create_tasklist"-method, but I do not know how to access it properly there. If I declare ´#a = params[:a]´ in the "create_tasklist"-method and then use (in create_tasklist.js.erb):
$("#task_list").html("<%= escape_javascript(render 'shared/task_list', a: #a) %>");
I recieve the error:
undefined method `collection_select' for "#<ActionView::Helpers::FormBuilder:0x4760400>":String
So the FormBuilder has become a string but a least it "got through" somehow. How can I leave it intact and is a more efficent way to achieve this?

Rails: passing value: view to controller to view with Javascript/Ajax

In one of my forms, I have an element called event_id which value I select from a dropdown box. Once I select event_id, I want to use Ajax to call the controller, and return panel_event_id as a ruby variable that I can use in the rest of the form. Here's what I'm doing:
In routes.rb, I have the following:
match 'panel_event_id', :to => "panels#event_id"
I have the following javascript function (not sure about the syntax):
<script type="text/javascript">
$('select').change(set_session_event_id);
function set_session_event_id()
{
var event_id = document.getElementById("event_id");
var event_id_value = event_id.value;
$.post('panel_event_id', { set_event_id: event_id_value });
}
</script>
What do I put in my panel_controler.rb, in the following method:
def panel_event_id
end
and how do I act on it back in my view?
You could render a json in your controller :
def panel_event_id
...
render :json => panel_event.as_json(:only => [ :id ])
end
After that, you could handle the success event of the post method. See the doc here : http://guides.rubyonrails.org/layouts_and_rendering.html and here http://api.jquery.com/jQuery.post/ and here http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json.

Categories

Resources