简体   繁体   English

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

[英]Ruby on Rails ActiveRecord::StatementInvalid in Customers#show

I have two models one is customer.rb and second is money.rb. 我有两个模型,一个是customer.rb,第二个是money.rb。 The relationships are customer has_many :money while money belongs_to customer. 关系是客户has_many:money,而钱属于客户。 I am using MySql Remote Database. 我正在使用MySql远程数据库。 When i try to extract data from single table at a time it just work fine, but the problem is when i try to do this: 当我一次尝试从单个表中提取数据时,它可以很好地工作,但是问题是当我尝试这样做时:

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

It throws an error: Mysql::Error: Unknown column 'money_tb.customer_id' in 'where clause': SELECT money_tb .* FROM money_tb WHERE money_tb . 它引发错误:Mysql :: Error:“ where子句”中的未知列“ money_tb.customer_id”:SELECT money_tb 。* FROM money_tb WHERE money_tb customer_id = ? customer_id =? Here is a snippet of my show.html.erb: 这是我的show.html.erb的片段:

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

Here is my customers_controller: 这是我的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

And this is the model: 这是模型:

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

end

Also i want to mention that customer_id field in money table is represented as "cid" 我也要提到,钱表中的customer_id字段表示为“ cid”

If you have different foreign_key name than "association_name_id" then you need to pass :foreign_key option to both belongs_to and has_many . 如果您具有与“ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM