Reputation: 13
I'm learning Ruby on Rails, I make a very simple app. This is the schema.rb:
ActiveRecord::Schema.define(version: 20160112141616) do
create_table "cities", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "state_id", null: false
end
add_index "cities", ["state_id"], name: "index_cities_on_state_id"
create_table "states", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
I loaded some states and cities. And I don't know how to make a query like this using Active Record:
SELECT cities.name, states.name FROM cities INNER JOIN states ON cities.state_id = states.id
I want to do that to print in a view, all of the cities names with their states names.
Thanks.
EDIT:
model city.rb:
class City < ActiveRecord::Base
belongs_to :states
validates :state_id, presence: true
end
model state.rb:
class State < ActiveRecord::Base
has_many :cities
end
cities_controller.rb:
class CitiesController < ApplicationController
def index
#@cities = City.all.order(state_id: :asc)
#@cities = State.joins(:cities).select('cities.name, states.name')
@cities = City.joins(:states).select('cities.name, states.name')
end
def new
@city = City.new
@states = State.all.order(name: :asc)
end
def create
@city = City.new(city_params)
if @city.save(:validate=> true)
redirect_to :back
else
render :new
end
end
def city_params
params.require(:city).permit(:name, :state_id)
end
end
Upvotes: 1
Views: 1451
Reputation: 33552
The below query will do
City.joins(:states).select("cities.name, states.name")
NameError: uninitialized constant City::States
The association name for the belongs_to
should be singular, so change states
to state
in city.rb
model
class City < ActiveRecord::Base
belongs_to :state
validates :state_id, presence: true
end
Upvotes: 1