我正在学习Ruby on Rails,我制作了一个非常简单的应用程序。 这是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
我装了一些州和城市。 而且我不知道如何使用Active Record进行这样的查询:
SELECT cities.name, states.name FROM cities INNER JOIN states ON cities.state_id = states.id
我想这样做是为了在一个视图中打印,所有的城市名称都带有州名。
感谢。
修改
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
答案 0 :(得分:0)
以下查询将执行
City.joins(:states).select("cities.name, states.name")
NameError:未初始化的常量City :: States
belongs_to
的 关联名称 应为 单数 ,因此请更改{{1在states
模型中的state
city.rb