RoR, Passing a variable into view gives a null object - ruby-on-rails-3

I am setting a variable in my controller but for some reason it is not getting set. I tried it two ways.
def update
# #available_cars = Car_info.where("user_id = ?", session[:user_id])
#available_cars = Car_info.find_by_user_id(session[:user_id])
end
In my view I do this.
<% #available_cars.each do |car| %>
<%= car.name %>
<% end %>
What I intend to do is populate the #available_cars into a drop down list but I can't even get them to print. I know the session[:user_id] is set because I print it and access it elsewhere.
I get this error...
Expected D:/RailsProjects/mileage/app/models/car_info.rb to define Car_info
in my controller
app/controllers/active_car_controller.rb:6:in `update'
Any help would be appreciated. New to RoR.

I see your controller method is named 'udpate' instead of 'update' - could that be your problem?

You need to change your query to:
#available_cars = Car_info.find_all_by_user_id(session[:user_id])
The find_all part will get you all records, whereas find only gets you the first. Another way to write this is:
#available_cars = Car_info.where("user_id = ?", session[:user_id])
Ideally, you want your class to be called CarInfo, not Car_info.

Related

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

Using #variable within link_to in Rails

I'm trying to make
<%= link_to #company.name, current_company %>
work. It does work, as long as I stay within the same profile page. As soon as I'm trying to leave it, I get the NoMethodError in StaticPages#about - undefined method `name' for nil:NilClass. I understand the problem lies within the controller (I guess?), but that's it. Can anybody point me in the right direction please.
UPDATED
Updating methods in my satic_pages controller to
def home
#company = Company.new
end
def about
#company = Company.new
end
helps with skipping the error, but instead of the company name the links start to look like
/companies/2
Update: Since you want your link to simply display the company name, you can just do something like <%= link_to #company.name, #company%>
In your controller, you want to reference which company you're linking to, so you can do something like #company = Company.last. This would take the last record that you created. Now, when you load your page, the link should take you to the show page for that company with the last company's name as the text for the hyperlink.

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.

Rails 3 - Object.try syntax

How would I avoid nil checks using Object.try for the following?
<%= image_tag(PeriodState.where("sla_id = ?", sla.id).last.state.image_file) %>
I've tried .try many different ways, but still receive errors, so my syntax is off. Thanks in advance!
try isn't really appropriate for this: whatever the outcome image_tag will always be called - so you might end up calling it with nil. You need to check whether the image exists first then create an image tag only in this case. So I would get the PeriodState in your controller and have a simple if in your view:
# in controller
#period_state = PeriodState.where("sla_id = ?", sla.id).last
# in view
<%= image_tag(#period_state.state.image_file) if #period_state %>
Of course this won't work if either state or image_file could also be nil.

Rails 3 - how to work with data got from database

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])