【问题标题】:Query from two tables active record从两个表的活动记录中查询
【发布时间】:2016-01-13 16:55:43
【问题描述】:

我正在学习 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

我想在视图中打印所有城市名称及其州名。

谢谢。

编辑:

模型城市.rb:

class City < ActiveRecord::Base
  belongs_to :states
  validates :state_id, presence: true
end

模型状态.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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    下面的查询会做

    City.joins(:states).select("cities.name, states.name")
    

    NameError: 未初始化的常量 City::States

    belongs_to关联名称应该是单数,因此将states 更改为@ 987654324@ 在city.rb 模型中

    class City < ActiveRecord::Base
      belongs_to :state
      validates :state_id, presence: true
    end
    

    【讨论】:

    • 试过你的解决方案,我得到了这个错误:irb(main):004:0> City.joins(:states).select('cities.name, states.name') NameError: uninitialized constant City::States 然后我尝试了这个: State.joins(:cities).select('cities.name, states.name') State Load (0.1ms) SELECT cities.name, states.name FROM "states" INNER JOIN " city" ON "cities"."state_id" = "states"."id" => #<:relation id: nil name: fe>, #, #
    • @kofran 你能在问题中发布你的模型代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多