I have two models one is customer.rb and second is money.rb. The relationships are customer has_many :money while money belongs_to customer. I am using MySql Remote Database. 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
. customer_id
= ? Here is a snippet of my 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:
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"
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
.
class Customer < ActiveRecord::Base
has_many :money, foreign_key: "cid"
end
class Money < ActiveRecord::Base
belongs_to :customer, foreign_key: "cid"
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.