View array or one record in rails view - ruby-on-rails

In my method via some calculations a get data, then i need to view it in view, but if write
#ar.each do |a|
when i have only one record i get error, also when i have one error each is bad idea. So how to do this this?
So i have such code in method:
non_original = []
#articles.each do |a|
non_original << get_non_tecdoc("LA44", 1, "KNECHT")
end
#non_original = non_original
get_non_tecdoc returns object, or nothing...
So in view i have:
-#non_original.each do |no|
=no.brand
=no.description
=no.price
=no.quantity
But what to do if #non_original has one record, then #non_original.each gives error. So how to do check in view? If #non_original has one record, than simple #non_original.brand etc, but if more than one, than use each loop?

This will work with #ar as a single value as well as an array:
Array(#ar).each do |a|
p a
end
This Array is a method on Kernel.

<%= debug #ar %>
This will give you a nice YAML format to look at in your view (assuming ERB).
EDIT: I believe this is what you want, since you're not interested in debugging.
In your controller, use the splat operator to convert a singleton element to an array (it doesn't modify arrays):
#ar = *#ar
Then #ar.each will work as expected in your view.
Alternatively, you could check in your view:
<% if #ar.is_a?(Array) %>
<% #ar.each ... %>
<% else %>
<%= #ar %>
<% end%>

Why don't you try using #ar.inspect and output it to the console to see the instance variables contents.

As long as #ar is an array you should not get a error. If you are returning one record change it to an array with one record.
If you are using active record query interface like the "where" clause; it will return an array with 0 or more active_record objects. If you use find it will return one instance of an active_record object.
So if your method that queries is using the active record where clause #ar should always return an array.

Please try this:
Tablename.find_by_table_id
Example:
if account_id is 10 then, take following example,
#getResults = Account.find_by_account_id(10)
It will gives single record.
we can get values using #getResults.id,#getResults.name ....like wise.

Related

How to display ROR 5 ActiveRecord pluck as String in html.erb

In html.erb I have:
<%= ContactDescribe.where(["contact_describe_id = ?", "12"]).limit(1).pluck(:borrower_or_lender_text) %>
The field is retrieved successfully. But returns an array element. I need to learn how to convert that element to a string.
In addition to Deepak's answer, you can also convert the Array into a "Sentence" String
<%= ContactDescribe.where(contact_describe_id: 12).limit(1).pluck(:borrower_or_lender_text).to_sentence %>
Recommendation:
As pointed out by TheChamp, it is best practice to already "prepare" the values needed in the views as instance variables from the controller. See my recommended refactor
# controller
def YOUR_ACTION_NAME
#contact_describe = ContactDescribe.where(contact_describe_id: 12).first
end
# view
<%= #contact_describe.borrower_or_lender_text %>
Note: you won't even need pluck anymore unless you have other reasons why you want limit(1)
The issue here is that where returns a collection - something similar to an array, just in ActiveRecord - no matter what limit you set on it. To retrieve the information you would use .first or [0] since you always only return one object.
But, since you are looking for a specific ContactDescribe object. Do this instead:
ContactDescribe.find_by(contact_describe_id: 12).borrower_or_lender
Additionally there two things you should improve in your code.
1: Logic should go into the controller or the model. A view is solely here to show objects.
2: What is up with the contact_describe_id field? Why not call it id. It seems redundant. Isn't user.id more convenient than user.user_id?
You can make use of join
<%= ContactDescribe.where(contact_describe_id: 12).limit(1).pluck(:borrower_or_lender_text).join(',') %>

Ruby Find last record value in has many

I'm trying to find the last Econ_Result that belongs to a Econ_Report. I want to display the last record of the Econ_Result (ordered by "release_date") for each Econ_Report on the index view. In the controller I tried to take the list of all reports and find the last result using the following:
#econ_reports = EconReport.all
if #econ_reports.econ_results.size >= 1
#last_result = #econ_report.econ_results.last.release_date
end
econ_report.econ_results.size works on the index view when I place it in for each loop. When I try to call the value of the last record I run into issues with the fact that some reports don't yet have results (a temporary issue) so I threw in the if then check in the controller which is currently failing.
Thanks in advance for the rookie help.
Since #econ_reports is a collection of EconReport objects, you can't call an instance method like .econ_results on it. Instead, you can only call it on instances within the collection:
#econ_reports.each do |econ_report|
if econ_report.econ_results.any?
last_result = econ_report.econ_results.last
end
end
However, this can be terribly inefficient for a large collection of #econ_reports: both lines with econ_report.econ_results will query the database separately, meaning that you'll query the database independently for each econ_report in the collection. This is known as the N+1 query problem.
Luckily for you, as discussed in the link, Rails has a built-in solution to optimize this code so you'll only query the database once:
<% #econ_reports.includes(:econ_results).each do |econ_report| %>
<% if econ_report.econ_results.any? %>
<% last_result = econ_report.econ_results.last %>
# do something to display last_result
<% end %>
<% end %>
If you just want the release date you might try:
#last_result = #econ_report.econ_results.order('release_date DESC').limit(1).pluck(:release_date).first
It's worth noting that a Ruby if statement generally looks like:
if condition
end
The then is almost always omitted even though it is allowed.

Ruby Active Record returns relation in Ruby on rails

I have this code
#devices_data=Hash.new
#devices.each do |device|
#devices_data[device.id.to_s] = #project.vibration_data.find(:all, conditions: { vibration_device_id: device.id })
end
But when I want to get data displayed in my view use following code:
<p><%= #devices_data %></p> //this show whole block of data
<p><%= #devices_data.first.id%></p> // it says undefined method `id' for # Array:0x000000058b0150
If I remove the hash container,just store data like(without define #device_data=Hash.new)
#devices.each do |device|
#devices_data = #project.vibration_data.find(:all, conditions: { vibration_device_id: device.id})
end
<p><%= #devices_data.first.id%></p> will display its id instead of error message.
But I have more than 1 data in each device, I do need an array or hash to hold this. But this give me problem.I tried add .first to make code as
#devices_data[device.id.to_s] = #project.vibration_data.find(:all, conditions: { vibration_device_id: device.id }).first
and I have also tried change find to where to retrieve data.
#devices_data[device.id.to_s] = #project.vibration_data.where(vibration_device_id: device.id ).first
But they doesn't work, in view still return me relation instead of value,which give me an error message.
Whats my problem? How can I solve it? Thank you!
<p><%= #devices_data.first.id%></p> // it says undefined method `id' for # Array:0x000000058b0150
gives you an error because #devises_data.first will bring back the first item of the hash as an array of [key, value]
if you try
<p><%= #devices_data.first.last.id%></p>
will print the id you are looking for, because #devised_data is a hash, first will give you the first element of the hash as an array of [key, value], when you send to the array the message last will give you back the value object, and then with id you will be getting the id you are looking for
.find(:all, :conditions => <cond>) is an old way of finding a set of active records. you should now use where(cond) instead, and it should work better for you.
where returns an Active Relation... which you can then use a final method on to fetch either all or just the first item matching your conditions.
when you then apply first it will pull the first item out of the active relation for you - which seems to be what you want.
... but then, because you are storing this value into a hash... you then have to either iterate through all the items in the hash using each, or use first again to fetch out the first item that you have put into the hash...
so something like:
#devices_data = {}
#devices.each do |device|
#devices_data[device.id.to_s] = #project.vibration_data.where( vibration_device_id: device.id ).first
end
<% #devices_data.each do |device_id, device| %>
<p><%= device_id %></p>
<p><%= device.name %></p> <!-- or whatever -->
<% end %>

.each breaking if only 1 result - rails

For some reason, I keep getting an "undefined method 'each'" error every time I try to do the .each do when I have one result in the below.
If I use .inspect, I can see that there's a match. Does .each work if there's not more than 1 result? If not, what should I use instead?
<% friends = graph.get_object("/me/friends").map{ |hash| hash["id"] } %>
<% User.select([:id]).where(fbookid: friends).each do |common| %>
<% end %>
If I just run .inspect on the User.select line (no each), then I get
[#<User id: 1>]
Any help would be appreciated!
Thank you!
UPDATE
Adding additional parameters seemed to allow me to use each...I have no clue why. It's the same exact result (only 1).
User.select([:id, :email, :first_name]).where(fbookid: friends).each do |friend|
You get simple object not array so that it's not working. .each method working when if you get array you get simple object so that you can use direct means that
for example
# if name attributes
User.select([:id]).where(fbookid: friends).name
You can use each on User.select([:id]).where(fbookid: friends), even if there is only 1 element. It will not raise an exception even if there are no elements.
The error is happening somewhere else. Perhaps you are getting an error on something inside the each loop.
Can you post more code?

What to use instead of find_with_ids( )?

The code below displays peferctly what i want to accomplish (show store name and item name).But when i subtitute #onedeal=#deal.find_with_ids(62) with #onedeal=#deal.find(params[:id]) i get an error Couldn't find Deal without an ID.What method should i use to fetch deal ID dynamically?The relationship between the Deal and store model is has many :through.
controller
#deal=#city.deals
#onedeal=#deal.find_with_ids(62)
#store=#onedeal.stores.first(params[:store_id])
view
<% #deal.each do |deal| %>
<%=deal.item_name %>
<%end%>
<%=#store.store_name %>
That error means that params[:id] is empty. Check your params hash to see what it contains, and verify that your action is getting the input it expects.
You are absolutely using the .find method as intended, so I don't think that's the issue.
What about
Deal.find(params[:id]) rescue nil

Resources