【问题标题】:Ruby on Rails ActiveRecord::StatementInvalid in Customers#showRuby on Rails ActiveRecord::StatementInvalid in Customers#show
【发布时间】:2016-08-22 06:36:52
【问题描述】:

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

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

它抛出一个错误:Mysql::Error: Unknown column 'money_tb.customer_id' in 'where clause': SELECT money_tb.* FROM money_tb WHERE money_tb.customer_id = ? 这是我的 show.html.erb 的 sn-p:

<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

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

【问题讨论】:

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


    【解决方案1】:

    如果您的 foreign_key 名称与“association_name_id”不同,那么您需要将 :foreign_key 选项同时传递给 belongs_to 和 has_many。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 2016-04-01
      • 2016-06-29
      • 2013-10-31
      相关资源
      最近更新 更多