Get distinct values from table - ruby-on-rails

I am trying to get distinct value from this controller. But I am not sure how to succeed.
Here the controller I have try this
#count = Present.where('event_id > ?', params[:id]).uniq.pluck(:customer_id)
But when I try to do this in my view
<% #count.each do | co | %>
<%= co.customer_id %>
<% end %>
I keep having this issues
Cannot visit Arel::Nodes::Distinct
I want to be able to preserve all Present Objects with the event_id equal to the id, but also being able to select only the one with distinct customer_id.
Update: after restarting the server i get the following error
undefined method `customer_id' for 1:Fixnum

Maybe you need to restart your rails server: https://github.com/rails/rails/issues/7399
Previous similar SO question
Update:
From the docs: When using pluck, "The values has same data type as column"
Change loop to:
<% #count.each %> do |i|
<%= i %>
<% end %>

Related

RAILS simpler way to pass an update form than create a new route?

I have an order record that has multiple pipe/ funnel positions ( pipe_part ) each recorded by creation of a pipe_record that records who and when for that part.
I'm trying to create an update button that will post an edit to alter data in the pipe_record , so i iterate through the orders records then create a form for each position that already has a pipe_record then i want to either destroy or update , however I cant filter my recordset to make a form_for it returns a key issue
<% #order.pipe.pipe_parts.order("priority").each do |part| %>
<% if #pipe_records.where("pipe_part_id= ?", part).present? %>
<td>
<% #pipe_position ||=part %>
<%= form_for #pipe_record.where("pipe_part_id= ?", part) do |f| %>
This throws a key error
undefined method `to_key' for # Did you mean? to_query to_ary
I created a second iteration of pipe_records in the controller incase was a cursor issue in the pipe_record recordset as below
#pipes=Pipe.all.order("name")
#pipe_records=#order.pipe_records
#pipe_record=#order.pipe_records
I tried to make an obj in the second itteration with
<% if #pipe_records.where("pipe_part_id= ?", part).present? do |pipe_record|%>
and then call
<%= form_for pipe_record do |f| %>
and am about to resort to creating a new route and controller for the update page as cant seem to get the id to pass to the #pipe_record but i know theres something obvious i've missed or structurally wrong in my solution.
.first !
I forgot #pipe_record was a collection
<%= form_for #pipe_record.where("pipe_part_id= ?", part).first do |f| %>
Resolved

How to sort a list containing a string alphabetically in rails view - rails 4

i am new to rails and any help would be much appreciated.
i am trying to sort my list by status, but i have string in code stating "Pending"
i believe the error is prompting up because it can not place the status in order because i have a string
could one kindly advise the best way to go about sorting out a list in alphabetical order where by the list contains a string - thank you
error message
comparison of String with nil failed
jobseekerpg.html.erb
<% #userj_applications.sort_by(&:status).each do |application| %>
<%= link_to application.advert.title, userr_advert_path(application.advert.userr, application.advert) %> |
<%= application.advert.city %> |
<%= application.advert.category_country.name %> |
<span>
status:
<% if application.status == nil %>
<%= "Pending" %>
<% else %>
<%= application.status %>
<% end %>
</span> |
applied: <%= application.created_at.strftime("%B %d, %Y") %><br>
<% end %>
static_controller.rb
class StaticPagesController < ApplicationController
respond_to :html, :xml, :json
def jobseekerpg
#userj = Userj.find(current_userj)
#userj_applications = #userj.forms
end
end
my suggestion:
i currently have a column named status in my table
do i create another column in my table called statusPending
make this as a hidden_field and assign it to pending statusPending:Pending
so whenever an application status is nill i can use an if & else statement to call up application.statusPending
but then i will not need to only sort by status , i will need to sort by status & statusPending
any advise or help will be much appreciated
could one kindly advise the best way to go about sorting out a list in
alphabetical order where by the list contains a string - thank you
Array#sort
stringList.sort!
The "array.sort!" should sort the list in-line.
Here are some ruby examples with blocks http://www.dotnetperls.com/sort-ruby
Looks like you are getting that error when the sort_by method tries to compare a non null status with a null one. You could try to replace your statement:
#userj_applications.sort_by(&:status).each do |application|
with
#userj_applications.sort {|x,y| (x.status || '') <=> (y.status || '') }.each do |application|
This way nil values are treated as empty strings during sort.

Rails shows rows from model, which aren't created

I have this part of code:
<% current_user.meta_accounts.each do |meta_account| %>
<%= content_tag(:li, link_to(meta_account.name, 'javascript:void(0)')) %>
<% end %>
So, I want Rails to show all my MetaAccounts in list, but I get this:
<li>Wallet</li>
<li>Credit card</li>
<li>Debit card</li>
<li>Debts</li>
<li>javascript:void(0)</li> #This is the problem
So, it also shows me MetaAccount, which isn't created yet.
In my MetaAccounts table I have this. I'm using Postgres.
So, it also shows me the last row, where row_number is *. I don't know why, and how to avoid this.
Thanks for any help!
Try:
<% current_user.meta_accounts.select(&:persisted?).each do |meta_account| %>
<%= content_tag(:li, link_to(meta_account.name, 'javascript:void(0)')) %>
<% end %>
The * row you see in PostgreSQL is not an actual record, it's just a quick way to create new records. If you want to be sure, run the following query:
SELECT COUNT(*) FROM MetaAccounts WHERE user_id=1
It will return 4.
I think the problem comes from an unsaved MetaAccount object in current_user.meta_accounts. This could be the case for instance in a form, where you build an empty object bound to the form. Make sure you don't have a call to current_user.meta_accounts.build(...).
If so, you can simply skip in your each loop all MetaAccount objects with a blank name.

execute sql query and loop through result set in rails

In my rails app, i have the following function in one of my controller page.
def tree
#jstree = ActiveRecord::Base.connection.execute("Select sequence, depth, node, imageid, range from.....several joins")
end
I now want to loop through the resultset and display the sequence only in my view page tree.html.erb. I tried the following code, it does not seem to work.
<% #jstree.each do |tree| %>
<%= tree.sequence %>
<% end %>
I am getting the error message: undefined method 'sequence' for #<Array:0x60e0088>.
Is there a way of looping through the result set of the sql query executed and displaying each column value?
Many many thanks for all suggestion provided :)
Keeping the same syntax as the OP
<% #jstree.each do |tree| %>
<%= tree[0] %>
<% end %>
would accomplish what you were looking for.
You get this error because what you get in #jstree is a raw DB adapter result. If you want to query for some objects by issuing raw SQL queries then use find_by_sql. Example:
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")

Rails 3.1 adding an object to an array returned by find_by_sql / can't show in erb file

I'm porting a php app to rails so I have a set of sql statements that I'm converting to find_by_sql's. I see that it returns a collection of objects of the type that I called on it. What I'd like to do is then iterate through this collection (presumably an array) and add an instance of a specific object like this:
#class is GlobalList
#sql is simplified - really joining across 3 tables
def self.common_items user_ids
items=find_by_sql(["select gl.global_id, count(gl.global_id) as global_count from main_table gl group by global_id"])
#each of these items is a GlobalList and want to add a location to the Array
items.each_with_index do |value,index|
tmp_item=Location.find_by_global_id(value['global_id'])
#not sure if this is possible
items[index]['location']=tmp_item
end
return items
end
controller
#controller
#common_items=GlobalList.common_items user_ids
view
#view code - the third line doesn't work
<% #common_items.each_with_index do |value,key| %>
<%=debug(value.location) %> <!-- works -->
global_id:<%=value.location.global_id %> <!-- ### doesn't work but this is an attribute of this object-->
<% end %>
So I have 3 questions:
1. is items an Array? It says it is via a call to .class but not sure
2. I am able to add location these GlobalList items. However in the view code, I cannot access the attributes of location. How would I access this?
3. I know that this is pretty ugly - is there a better pattern to implement this?
I would get any data you need from locations in the sql query, that way you avoid the n+1 problem
#items=find_by_sql(["select locations.foo as location_foo,
gl.global_id as global_id,
count(gl.global_id) as global_count
from main_table gl
inner join locations on locations.global_id = gl.global_id
group by global_id"])
Then in the view:
<% #items.each do |gl| %>
<%= gl.location_foo %> <-- select any fields you want in controller -->
<%= gl.global_count %>
<%= gl.global_id %>
<% end %>
If you want to keep it close to as is, I would:
def self.common_items user_ids
items=find_by_sql(["select gl.global_id, count(gl.global_id) as global_count
from main_table gl group by global_id"])
items.map do |value|
[value, Location.find_by_global_id(value.global_id)]
end
end
Then in the view:
<% #common_items.each do |value,location| %>
<%=debug(location) %>
global_id:<%=value.global_id %>
<% end %>

Resources