2016-01-13 34 views
0

我在學習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 

我裝一些州和城市。 我不知道如何做一個這樣的查詢使用活動記錄:

SELECT cities.name, states.name FROM cities INNER JOIN states ON cities.state_id = states.id 

我想要做的是,在一個視圖中進行打印,所有城市的名字與他們的國家的名字。

謝謝。

編輯:

模型city.rb:

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

模型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

下面的查詢會做

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

NameError: uninitialized constant City::States

協會名稱belongs_to應該奇異,所以在city.rb模型改變statesstate

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

試過你解決方案,我得到這個錯誤: IRB(主要):004:0> City.joins(:狀態)。選擇( 'cities.name,states.name') NameError:未初始化的常量市::美國 然後我嘗試這樣的: 國家.joins(:cities).select('cities.name,states.name') State Load(0.1ms)SELECT cities.name,states.name FROM「states」INNER JOIN「cities」ON「cities」。「state_id 「=」狀態「。」id「 =>#,#,#<國家ID:無,名稱:「聖達菲」> – kofran

+0

@kofran你可以在問題中發佈你的型號代碼。 – Pavan

+0

感謝Pavan,我編輯了原始問題。 – kofran