Reputation: 38832
I have two model classes: Cars and Customers,
Model Cars:
class car < ActiveRecord::Base
#car has attribute :town_code
has_many :customers
end
Model Customers:
class customer < ActiveRecord::Base
# customer has attribute :first_name, :last_name
belongs_to :car
end
In my controller, I have the following code:
my_customer = Customer.find_all_by_first_name('John')
p my_customer.last_name
p my_customer.car_id
But I got no attribute 'car_id'
error, I also got no attribute 'last_name'
error.
---Question 1:---
I checked my database, I do have 'car_id' and 'last_name' columns on my customer table. Why I can not access them in the way how my controller code does?
---Question 2:---
but the code : my_customer.map(&:car_id)
is working for accessing car_id, however, I do not quite understand the code .map(&:car_id)
, what does it do? Can anyone explains to me?
Upvotes: 0
Views: 807
Reputation: 51052
The reason you aren't able to do my_customer.last_name
is that my_customer
is not a Customer here but an array of Customers, since you did find_all
. That's also why my_customer.map(&:car_id)
works. What that bit of code means is: For each object in the array my_customer, call the method car_id
and insert the results into a new array -- and return that new array.
If customer belongs to car, you need a car_id in the customer table (which corresponds to an id column in the car table). Also, you shouldn't have last_name in the car table, but rather in the customer table.
It sounds like you may need to step back and gain a better understanding of ActiveRecord associations. It's not clear to me why a customer would belong_to a car, anyway.
Upvotes: 2