客户#show中的Ruby on Rails ActiveRecord :: StatementInvalid

时间:2016-08-22 06:36:52

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

我有两个模型,一个是customer.rb,第二个是money.rb。 关系是客户has_many:钱而钱属于客户。我正在使用MySql远程数据库。当我尝试一次从单个表中提取数据时它工作正常,但问题是当我尝试这样做时:

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

它抛出一个错误:Mysql :: Error:'where子句'中的未知列'money_tb.customer_id':SELECT money_tb。* FROM money_tb WHERE money_tb。{{1 }} =? 这是我的show.html.erb的片段:

customer_id

这是我的customers_controller:

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

这是模特:

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

另外我想提一下money表中的customer_id字段表示为“cid”

1 个答案:

答案 0 :(得分:0)

如果你有不同的foreign_key名称而不是&#34; association_name_id&#34;然后,您需要将: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