Get referenced objected fields from postgresql using node.js - javascript

i have tow tables in postgres database, account_invoice and res_partner. account_invoice has a relational field of res_partner referenced using id (primary key).
while querying account_invoice the res_partner is appearing as integer instead of name. to solve this i am running another query inside the account_invoice to look up for the res_partner object name field i can view that by logging in the console but cannot render it in the html.
here is my code.
<div flex class="main-container">
<%- include(page) %>
<ul>
<% markers.forEach(function (result) { %>
<li><%= result.invoice_number %></li>
<% var name = pg.search('res_partner where id = ' + result.partner_id, function(person) { %>
<% console.log(result.invoice_number + " / " + person[0].name) %>
<li><%- 'Customer name ' + person[0].name %></li>
<% }) %>
<% }) %>
</ul>
</div>

Related

How to make multiple loadmore buttons assigned to each individual list on one page

Hello I have 3 lists on one page that will display and each list has a load more button. I want to be able to click the loadmore button and load 3 items per click.
The problem that I am facing is that when i click the load more button, the second page doesnt show up but on the 2nd click it populates only the last page.
Another is when for instance the button is clicked on completed and then clicking the button on expired creates duplicates of the expired list.
So pretty much the all of the buttons are changing all of the lists eventhough they are not corresponding to them.
I realize that im using url_for which may be the reason im in this problem. perhaps there is a better way to achieve this?
When clicking load more button on the console i get:
www.mywebsite.com/your_essays?page_completed=2".
www.mywebsite.com/your_essays?page_completed=3".
www.mywebsite.com/your_essays?page_expired=2".
This shows what the current page is based on the url, however if i have multiple lists how can i achieve this to make each list separate from each other? is there a better way to do this??
reservations_controler.rb:
def your_essays
user = current_user
#reservations = user.reservations.where("user_id = ?", current_user.id).where("status = ?", true)
#pending
#reservations_pending = user.reservations.where("turned_in = ?", false).where("completed = ?", false).where("due_date >= ?", DateTime.now).order(created_at: :desc).page(params[:page_pending]).per_page(3)
#reservations_pending1 = user.reservations.where("turned_in = ?", false).where("completed = ?", false).where("due_date >= ?", DateTime.now).order(created_at: :desc)
#completed
#reservations_completed = user.reservations.where("turned_in = ?", true).where("completed_doc_updated_at <= due_date", true).order(created_at: :desc).page(params[:page_completed]).per_page(3)
#reservations_completed1 = user.reservations.where("turned_in = ?", true).where("completed_doc_updated_at <= due_date", true).order(created_at: :desc)
#expired
#reservations_expired = user.reservations.where("due_date <= ?", DateTime.now).where("turned_in = ?", false).where("completed = ?", false).order(created_at: :desc).page(params[:page_expired]).per_page(3)
#reservations_expired1 = user.reservations.where("due_date <= ?", DateTime.now).where("turned_in = ?", false).where("completed = ?", false).order(created_at: :desc)
end
my_essays.html.erb:
<div id="content-load-more-completed">
<%= render 'your_essays_completed', reservations_completed: #reservations_completed %>
</div>
<% unless #reservations_completed.current_page == #reservations_completed.total_pages %>
<div id="view-more-completed" class="center" style="min-width:100%;" >
<%= link_to('View More', url_for(page_completed: #reservations_completed.current_page + 1), remote: true, class: 'btn btn-back', style: 'min-width:100%;') %>
</div>
<% end %>
<div id="content-load-more-expired">
<%= render 'your_essays_expired', reservations_expired: #reservations_expired %>
</div>
<% unless #reservations_expired.current_page == #reservations_expired.total_pages %>
<div id="view-more-expired" class="center" style="min-width:100%;" >
<%= link_to('View More', url_for(page_expired: #reservations_expired.current_page + 1), remote: true, class: 'btn btn-back', style: 'min-width:100%;') %>
</div>
<% end %>
my_essays.js.erb:
$('#view-more-completed').click(function (event) {
$('#content-load-more-completed').append("<%=j render 'your_essays_completed', reservations_completed: #reservations_completed, format: 'html' %>");
});
<% if #reservations_completed.current_page == #reservations_completed.total_pages %>
$('#view-more-completed').remove();
<% else %>
$('#view-more-completed a').attr('href', '<%= url_for(page_completed: #reservations_completed.current_page + 1) %>');
<% end %>
$('#view-more-expired').click(function (event) {
$('#content-load-more-expired').append("<%=j render 'your_essays_expired', reservations_expired: #reservations_expired, format: 'html' %>");
});
<% if #reservations_expired.current_page == #reservations_expired.total_pages %>
$('#view-more-expired').remove();
<% else %>
$('#view-more-expired a').attr('href', '<%= url_for(page_expired: #reservations_expired.current_page + 1) %>');
<% end %>
partials for _your_essays_completed.html.erb and _your_essays_expired.html.erb:
<% reservations_completed.each do |reservation| %>
<!-- content -->
<% end %>
<% reservations_expired.each do |reservation| %>
<!-- content -->
<% end %>

Access form_group div via id

I want to perform a check to provide instant validation feedback on the input of a field in my bootstrap form for my Profiles model using java/coffee-script. My current solution is working but feels rather clunky and I would like to improve it.
Here are some code examples of what I'm doing.
app/views/profiles/_form:
<%= bootstrap_form_for(#profile, layout: :horizontal, html: {id: "profile-form"} ) do |f| %>
<%= f.text_field :name %>
<%= f.text_field :number, id: "number-field" %> //Field to check
<%= form_group do %>
<%= f.primary %>
<% end %>
<% end %>
app/assets/javascript/profile_number_control.coffee:
$(document).on 'ready page:load', ->
$field = $("#number-field")
$group = document.getElementById("profile-form").childNodes[5]
numberPattern = "^(19|20)[0-9]{6}-[0-9]{4}$"
$helpBlock = $group.getElementsByClassName("help-block")[0]
$field.keyup ->
//This works fine, just wanted to show what is going on
if inputIsValid()
set $group class to " has-success"
set $helpBlock message to successful
else
set $group class to " has-error"
set $helpBlock message to corresponding error message
Here is the problem. I want this script to work for both profile#new and profile#edit, but since the array of elements given by document.getElementById("profile-form").childNodes differs in length depending of the current view I can not use the same index (5 in the example) for both #new and #update.
Does anyone know how to set an id to that specific form_group in my view? Or do I have to actually write out the whole html code to be able to place an id there properly?
This might help !
<%= bootstrap_form_for(#profile, layout: :horizontal, html: {id: "profile-form"} ) do |f| %>
<%= f.text_field :name %>
<%= f.text_field :number, :input_html => { id: "number-field" } %> //Field to check
<%= form_group do %>
<%= f.primary %>
<% end %>
<% end %>

Rails - refreshing page with new table entries

The goal I am trying to achieve is to let the user click on a button which will refresh to page filter that search. My page is dedicated to music artists and would like that once the user selects "Pop", that the page refreshes showing only "pop" artists.
Here is the html + ruby that I am using to display the artists:
<% #prints the artists that match the search, prints all for empty search %>
<% #artists.each_slice(3) do |artists| %>
<div class="row">
<% artists.each do |artist| %>
<div class = "artist_images">
<%= link_to image_tag(artist.artist_art, class: 'show_image'), artist_path(artist) %><br/><br/>
</div>
<% end %>
</div>
<% end %>
<% #prints message showing that the search does not match %>
<% if !#artists.present? %>
<h3><center style = "color: white">There are no artists containing the term(s) "<%= params[:search] %>". Please try 'Adele', 'Drake', 'Kanye West', or 'Taylor Swift'</center></h3>
<% end %>
The controller has the following methods:
def index
#artists = Artist.all
end
def randomPop
#artists = Artist.where(:genre => "\nPop").random(9)
end
Does anyone know how I can go about changing the variable #artists from All artists to those in pop only through a button click?
in your view,
<%= button_to "Pop", artists_path, method: :get, params: { artist_genre: "Pop" } %>
in your controller,
def index
if params[:artist_genre]
#artists = Artist.where(:genre => params[:artist_genre]).random(9)
else
#artists = Artist.all
end
end
This classic railscast episode is on point. I would use that for how you set up your search box. The only thing you might alter/update:
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
Should probably be a where clause based on your situation"
if search
where("genre = ?", your_genre)
else
all
end

Rails: Populate inputs from a select tag in form

I'm running Rails 4 and Ruby 2.
I am creating an app where you can track your calories and macronutrients through each meal you eat.
I'm adding a meal favourites page where the user can add meals they consistently eat. I have done this through a favourites:boolean migration.
When a user creates a new meal I want to show them a drop down box of favourites they have already saved, by something like current_user.meals.where(favourite: true).
When they click on one of their favourites from the drop down I would then like that information to populate the protein, carbs and fat inputs in the form.
What is the best way to do this?
MealsController:
class MealsController < ApplicationController
.
.
.
def new
#meal = current_user.meals.build
end
def create
#meal = current_user.meals.build(meal_params)
respond_to do |format|
if #meal.save
format.html { redirect_to root_path, notice: 'Meal was successfully added.' }
else
format.html { render action: 'new', notice: 'Meal was not added.' }
end
format.js
end
end
.
.
.
private
def set_meal
#meal = Meal.find(params[:id])
end
.
.
.
end
New/Edit Meal Form
<%= form_for(#meal) do |f| %>
.
.
.
<div class="field inline">
<%= f.label :protein %> (g)<br>
<%= f.text_field :protein %>
</div>
<div class="field inline middle">
Carbs (g)<br>
<%= f.text_field :carbohydrates %>
</div>
<div class="field inline right">
<%= f.label :fats %> (g)<br>
<%= f.text_field :fats %>
</div>
<div class="field actions">
<%= f.check_box :favourite, class: "favourites" %> Add to Favourites?
</div>
<div class="actions">
<%= f.submit "Save", class: "btn btn-large" %>
<% if current_page?(edit_meal_path(#meal)) %>
<%= link_to "Delete", #meal, class: "btn btn-large", method: :delete, data: { confirm: "Are you sure?" } %>
<% end %>
</div>
<% end %>
Thanks!
You can do it with JavaScript/jQuery:
$(document).ready(function() {
bindFavoriteMeal();
});
function bindFavoriteMeal() {
$('#favorite_meal_select').change(function() {
var mealId = $(this).val();
var url = "/meals/" + mealId
$.getJSON(url, function(data) {
$.each(data, function(key, value) {
var field = $("#" + key);
if (field.length) {
field.val(value);
}
});
});
});
}
The show action in your meals controller will have to respond to JSON, and you need to ensure that the form ids match with the JSON keys returned. The JSON could look like:
{ 'name': 'Mustart Salmon', 'protein': 40, 'carbs': 8, 'other_stuff': 'some_value' }
See Rails Controller Overview: Rendering JSON.
The implementation of the select dropdown will depend on what it's for. Is it for associating an item from the dropdown with the object being created? In that case check out the other answer by #jordan-davis. Or is it merely to inform the user of previously made choices? In that case I'd recommend options_for_select. There are a lot of built-in helpers for selects:
ActionView Form Options Helpers
You would populate the dropdown with collection select
<%= collection_select :user, :meal, Meal.all, :id, :name, checked: meal.name.first %>
This code won't cut and paste, but it's to show the idea. After that, you would have to use jQuery to grab the meal id, and then use that to populate the rest of the info. You would start with something along the lines of:
$(".dropdown-menu li a").click(function(){
$(this).parents(".dropdown-menu:first").dropdown('toggle')
var selectedMeal = $(this).text();

Jquery Tokeninput & Dynamic Nested Forms

I am using the setup of the R.B. railcast - #197 Nested Model Form Part 2 to dynamically add fields to the form but i am having issues getting the Tokeninput fields to work.
Form:
<%= form_for(current_user, :url => user_products_path) do |f| %>
<%= f.error_messages %>
<%= f.fields_for :user_products do |builder| %>
<%= render "user_product_fields", :f => builder %>
<% end %>
<%= link_to_add_fields "Add a UserProduct", f, :user_products %>
<%= f.submit "Create" %>
<% end %>
This is my user_product_fields partial, the token text_fields are what I'm having the issue with:
<div class="fields">
<%= f.label :product_token, "Product" %>
<%= f.text_field :product_token, :id => 'product_token' %>
<%= f.label :address_token, "Address" %>
<%= f.text_field :address_token, :id => 'address_token' %>
<%= f.label :price %>
<%= f.text_field :price %>
<%= link_to_remove_fields "remove", f %>
</div>
Jquery Tokeninput functions inside of my application.js:
$(function() {
$("#product_token").tokenInput("/products.json", {
prePopulate: $("#product_token").data("pre"),
tokenLimit: 1
});
});
$(function() {
$("#address_token").tokenInput("/business_addresses.json", {
prePopulate: $("#address_token").data("pre"),
tokenLimit: 1
});
});
What the nested form does in the function is this:
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).parent().before(content.replace(regexp, new_id));
}
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}
This line here:
var new_id = new Date().getTime();
Makes the tokeninput fields dynamic, this is what i pulled up from the HTML, notice the changing long numbers in the fields. This is because of the line above.
<label for="user_user_products_attributes_1313593151076_product_token">Product</label>
<label for="user_user_products_attributes_1313593146876_product_token">Product</label>
<label for="user_user_products_attributes_1313593146180_product_token">Product</label>
How can i get my token fields to work when the fields keep changing up?
Thank you.
EDIT: New working code.
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(content.replace(regexp, new_id)).insertBefore($(link).parent()).trigger("nestedForm:added");
}
$('div.fields').live("nestedForm:added", function() {
$("#product_token", $(this)).tokenInput("/products.json", {
prePopulate: $("#product_token", $(this)).data("pre"),
tokenLimit: 1
});
});
When trying to data-pre with TokenInput:
def new
#user_product = current_user.user_products.build
# This line below is for TokenInput to work, This allowed me to use #products.map on the form.
#products = []
end
def edit
#user_product = UserProduct.find(params[:id])
# This line below had to find the Product associated with the UserProduct
#products = [#user_product.product]
end
You can user jQuery's insertBefore instead of before as that will return the inserted element. It will help you to trigger some event. You can have a listener on this event, in which you can have you token-input code. You should also use class instead of id, as many elements can have same class, but no two elements should have same id.
$(content.replace(regexp, new_id)).insertBefore($(link).parent()).trigger("nestedForm:added");
$('div.fields').live("nestedForm:added", function() {
$(".product_token", $(this)).tokenInput("/products.json", {
prePopulate: $(".product_token", $(this)).data("pre"),
tokenLimit: 1
});
});
This is just an idea, code is not tested.

Categories

Resources