Selecting From A Different Table

P

Paul Thomas

How do I select records from a table that has a different name than my
controller?

My example is as follows

in locations_controller.rb

class LocationsController < ApplicationController

def new
@location = Location.new
@regions = #Needs to do a find:)all) to populate from regions table
end
 
J

James Edward Gray II

How do I select records from a table that has a different name than my
controller?

My example is as follows

in locations_controller.rb

class LocationsController < ApplicationController

def new
@location = Location.new
@regions = #Needs to do a find:)all) to populate from regions table
end

I believe you are looking for:

@regions = Region.find:)all)

Assuming I guess your model name correctly. Just remember that find
() is just a method call on some model.

Hope that helps.

James Edward Gray II
 
P

Paul Thomas

James said:
I believe you are looking for:

@regions = Region.find:)all)

Assuming I guess your model name correctly. Just remember that find
() is just a method call on some model.

Hope that helps.

James Edward Gray II

Thanks for the prompt reply. When I call @regions = Region.find:)all)
the @regions is empty. Region is my model name as well.

Here are my models that are of importance to this.

class Region < ActiveRecord::Base
has_one :location
end

class Location < ActiveRecord::Base
belongs_to :region
end

And from the controller
def new
@location = Location.new
@regions = Region.find:)all) # @regions is still empty
end

And lastly, from the view (_form.rhtml -- used in edit.rhtml and
new.rhtml)
<% collection_select("location", "region_id", @regions, "id", "name") %>
 
W

Wilson Bilkovich

Try putting <%=3D debug(@regions) %> on your _form.rhtml, above the
collection_select call.
I believe you'll find that the regions are there, it's just that your
select call isn't quite right. (Should be <%=3D, not <%, by the way)

Try this:
def new
@location =3D Location.new
@regions =3D Region.find:)all)
@region_options =3D @regions.zip(@regions)
end

..and then, in the form:
<%=3D select('location', 'region_id', @region_options) %>

--Wilson.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top