Rails 3 - how to work with data got from database - ruby-on-rails-3

I am loading from database the only row. The data are stored in variable (e.g.) #data.
In view, if I want to display the value got from database, I have to do following:
<% #data.each do |d| %>
<%=d.name %>
<%end%>
And I would like to ask you - exist any better way? I think it's a bit silly for the only row to use loop... I tried something like
<%= #data.name %>
OR
<%= #data.each.name %>
But in both cases I got the error message about bad syntax...
So to my question - is possible to get display data a bit more elegantly?
EDIT: my query: #data = Car.includes(:tyres).where("param1 = ?", params[:param1])

If you've loaded more than one model (row), then a loop is the natural construct for displaying each value. If you're really set on a one-liner, you could use some of Ruby's list comprehensions:
<%= #data.map(&:name).join(" ") -%>

I think that you are loading .all instead of .first.
In your controller,
#data = Data.where(:some => 'condition').first
or
#data = Data.find(params[:id])

Related

Ruby Postgresql Sort database table info by specific column's data in a loop

I don't even know how to ask this correctly, so pardon me if my question is confusing. I have a Table called Colors -
I would like to iterate a list of all the colors in the table, but presorted by 'color-family' so the result would look something like this:
Colors:
Reds -
Maroon
Stop Sign
Yellows -
Canary
Blues -
Sky Blue
Royal Blue
Greens -
Neon Green
But I have no idea the sql syntax to collect and sort that kind of information.
Surprisingly, this code didn't work ;)
<% #group = Colors.presort_by("color-family") %>
<% #color = Colors.all %>
<% #group.each do |group| %>
<%= group.color-family %>s - <br>
<% if #color.name.has_a_column_that_is_also_the_#group.color-family %>
<%= #color.name %>
<% end %>
<% end %>
lol. As you can see, I have no real idea where to start. Any help would be greatly appreciated. I don't have any sql query experience whatsoever.
Thanks again!
I'm not sure if there's a way to do this using just ActiveRecord query methods. But it can easily be done in-memory using Ruby's Enumerable#group_by, and the performance will be good unless it's a large data set (in which case you'd probably want to cache the results, or look into a more complex SQL query)
#colors = Color.all
grouped = #colors.group_by { |color| color.color_family }
# or .group_by &:color_family
This will return a hash where keys are color family (strings) and values are arrays of Color records.

Null vs Nil in database

I am using an SQLite3 database with my rails app and am having a very frustrating time trying to solve this problem.
I want to populate check boxes in a different manner depending on if the form (_form.html.erb) is being rendered in update or in create so:
<% if #foo.new_record? %>
<% query = "association_id == nil" %>
<% else %>
<% query = "" %>
<% end %>
and then I pass the query string to my check boxes
collection_check_boxes(:host, :association_ids, Association.where(query), :id, :name)
What this should do is give me all of the associations as check boxes for update and only ones that don't already have an association_id when creating.
If I replace the query with :association_id=>nil I will get the desired result for create.
If I replace the query with Association.all, I get the result for update.
I could just replicate all of my code manually in the check for new_record? but my code is already rather long and complicated and that would make it doubly so. So I wanted to just pass a string (query) to my where call. This is where I ran into trouble.
When I look in the rails console and make direct SQL queries I notice that returned files without an association_id will show up as association_id: nil. So I try to match to nil but that gives me an "unknown column: nil" error from SQL. When I try to match to the SQL NULL it doesn't find anything.
How is a nil attribute stored in the database and how do I query to find it using a string?
You should do
<% query = "association_id is null" %>
Association.where(:association_id => nil)
will be converted internally into a query like below
select * from associations where association_id is null

Editing multiple records at once - how to update without IDs

Still new to Rails. I'll try to provide as much detail as possible.
I have a form that lets me update multiple records at one time.
It's based off the 'Editing Multiple Individually' Railscast episode.
<%= form_tag(auction_clerk_path(#auction), :method => :put) do %>
<% #lots.each do |lot| %>
<%= fields_for "lots[]", lot do |f| %>
<%= f.number_field :sale_price %>
<% end %>
<% end %>
<% end %>
(Simplified to just include a single input for each instance)
An Auction contains multiple Lots (items for sale).
The auction_clerk_path is the route I'm using to just show all lots on one auction.
Everything is working just fine... until I use try to customize my lot paths...
I've added the following to my lot.rb file to be able to use:
/auctions/:auction_id/lots/:lot_number
instead of /auctions/:auction_id/lots/:id
def to_param
lot_number
end
So, in the form mentioned earlier, the fields render with name="lots[12][sale_price]" where 12 is the id.
However with the to_param change, now the fields render with name="lots[1][sale_price]" where 1 is the lot_number.
When I save, the submitted parameters are lot_numbers instead of ids.
So obviously when it tries to update, it won't find the correct records.
My method definition looks like this:
def save_clerking
#updated_lots = Lot.update(params[:lots].keys, params[:lots].values).reject { |l| l.errors.empty? }
if #updated_lots.empty?
flash[:notice] = "Lots updated"
redirect_to auction_clerk_path(#auction)
else
render :action => "clerk"
end
end
I either need to change my method definition to lookup by lot number, or change the form to somehow output IDs in the first place... but I don't know how.
Any help is appreciated. Thanks!
Fixed this through some help on another question.
I changed my method def to
#updated_lots = []
params[:lots].each do |lot_number, attributes|
lot = Lot.where("lot_number = ? AND auction_id = ?", lot_number, params[:auction_id]).first
if lot.update_attributes(attributes)
#updated_lots << lot
end
end
You could fetch the ids by lot number in the controller action and feed those to the update method instead of the params keys.

Mapped array error in Rails 3

I've spent 3 days trying to write scopes in models. At this point i don't care about producing the optimum solution... i just want to get this to work. In a rails 3 app i have the following code in the controller.
#questions = Question.all
#ans = Answer.where(user_id = current_user.id)
#answers = #questions.map { |q| [q, #ans.find_by_question_id(q.id)] }
Each answer record has a question_id field so it can be linked to the appropriate question. I am trying to get the answers array to list out in the same order as the questions.
The following code in a view renders the answers but not in the correct order.
<% #ans.each do |q| %>
<%=q.score%><br/>
<% end %>
I then changed the array to the mapped array which should produce the answers in the appropriate order.
<% #answers.each do |q| %>
<%=q.score%><br/>
<% end %>
I get the following error:
undefined method `score' for #<Array:0x10335ef90>
Any help is appreciated. Thanks.
Instead of q.score you probably want q[1].score, since q is really a two-item array of the question and answer. The second item (q[1]) will give you the answer.
This is because q is not an Answer, but an array containing both a Question and an Answer. So you could just change it to q[1].score. A nicer way is to break out the array in the block variables, like so (note the parentheses):
<% #answers.each do |(question, answer)| %>
<%= answer.score %><br/>
<% end %>

Running a SQL query in rails

I have a rails application where I have to subtract 2 time stamps and display the result on the webpage
I have used the following sql statement and I am getting the results.
select (julianday(resolutions.created_at)-julianday(tickets.created_at))*24 from tickets,resolutions
the value of tickets.created_at is 2010-04-05 18:59:02 which is a time stamp and value of resolutions.created_at is 2010-04-08 08:10:33
Now where do I put this sql so that I can be seen in my webpage.
I tried it in the views page with the following but nothing showed up:
<% #sql = "select (julianday(resolutions.created_at)-julianday(tickets.created_at))*24 from tickets,resolutions" %>
<% #t=(ActiveRecord::Base.connection.execute(#sql)) %>
So how do I display it on my webpage?
when I perform the above I get the output printed on the webpage as
061.1919444389641(julianday(resolutions.created_at)-julianday(tickets.created_at))*2461.1919444389641
only 61.1919444389641 is supposed to be printed but the query statement is also getting printed.
You should put your custom SQL in your model class, definitely not in the view.
In your controller
#tickets = Tickets.find(
:all,
:joins => :resolution,
:select => '(julianday(resolutions.created_at)-julianday(tickets.created_at))*24 AS interval'
)
In your view
<% #tickets.each do |ticket|%>
<%= ticket.interval %>
<% end %>
Generally you would put this logic in one of your models though, like this:
In your Tickets Model
def time_to_resolve
resolution.created_at - created_at
end
To reduce the number of queries when iterating over multiple queries you would use this:
Tickets.find(:all, :include => :resolution)