Ruby on rails 从两个表中查询活动记录
我正在学习RubyonRails,我制作了一个非常简单的应用程序。 这是schema.rb:Ruby on rails 从两个表中查询活动记录,ruby-on-rails,ruby-on-rails-4,rails-activerecord,Ruby On Rails,Ruby On Rails 4,Rails Activerecord,我正在学习RubyonRails,我制作了一个非常简单的应用程序。 这是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:
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
城市控制器.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
下面的查询就可以了
City.joins(:states).select("cities.name, states.name")
NameError:未初始化的常量City::State
所属对象的关联名称应为单数,因此在city.rb模型中将states更改为state
尝试了您的解决方案,但我遇到了以下错误:irbmain:004:0>City.joins:states.select'cities.name,states.name'NameError:uninitialized constant City::states然后我尝试了以下操作:State.joins:cities.select'cities.name'State Load 0.1ms select cities.name,states.name FROM states internal JOIN cities ON cities.state_id=states.id=>@kofran您能在问题中发布您的模型代码吗。
class City < ActiveRecord::Base
belongs_to :state
validates :state_id, presence: true
end