2016-08-22 236 views
0

我有兩個模型,一個是customer.rb,第二個是money.rb。 關係是客戶has_many:金錢belongs_to客戶。我正在使用MySql遠程數據庫。當我嘗試在同一時間,它只是正常工作來提取單個表中的數據,但問題是,當我嘗試這樣做:Ruby on Rails ActiveRecord :: StatementInvalid在客戶中#show

<%= @customer.money.each do |m| %> 
    <%= m.id %> 
    <%= m.cid %> 
<% end %> 

它拋出一個錯誤的:mysql ::錯誤:未知列「money_tb。 customer_id'in'where clause':SELECT money_tb。* FROM money_tb where money_tbcustomer_id =? 這裏是我的show.html.erb的一個片段:

<h1><%= @customer.name %></h1> 
<%= @customer.money.each do |m| %> 
    <%= @m.id %> 
    <%= @m.cid %> 
    <%= @m.customer.name %> 
<% end %> 

這裏是我的customers_controller:

class CustomersController < ApplicationController 
    def index 
     @customers = Customer.all 
    end 

    def new 
     @customer = Customer.new 


    end 
    def create 
     @customer = Customer.new(customer_params) 
     if @customer.save 
      flash[:notice] = "Customer Create" 
      redirect_to new_customer_path 
     else 
      render 'new' 
     end 

    end 

    def edit 
     @customer = Customer.find(params[:id]) 

    end 
    def update 
     @customer = Customer.find(params[:id]) 
     if @customer.update(customer_params) 
      flash[:notice] = "Customer Updated" 
      redirect_to customers_path 
     else 
      render 'edit' 
     end 
    end 
    def show 
     @customer = Customer.find(params[:id]) 
    end 
    private 
    def customer_params 
     params.require(:customer).permit(:name, :address, :ph_no) 
    end 



end 

這是模型:

class Customer < ActiveRecord::Base 
    self.table_name = "cust_tb" 
    has_many :money 
    has_many :gold 

end 

我也想提一下貨幣表中的customer_id字段表示爲「cid」

回答

0

如果您有不同的f oreign_key名稱比「association_name_id」那麼你需要通過:foreign_key選項belongs_tohas_many

class Customer < ActiveRecord::Base 
    has_many :money, foreign_key: "cid" 
end 

class Money < ActiveRecord::Base 
    belongs_to :customer, foreign_key: "cid" 
end 
+0

非常感謝#Michal_Mlozinak。它的工作,謝謝你.... –