ruby on rails - Has and belongs_to many or has_many through example with active record -


let's have fictional car rental application.

i have users, cars, , addresses.

user (id, name, email)   has_many :addresses   has_many :cars  car (id, name)   belongs_to :user  address (id, name, user_id)   belongs_to :user 

each user has multiple addresses , cars. address location user can lend car.

now, model, following (let's user #1 has 2 addresses , 3 cars):

settings user #1 :  (specify @ address each of cars available) /-------------------------------------------\ |           |  car #1  | car #2  |  car #3  | |-----------+----------+---------+----------| | address 1 |   yes    |  yes    |    no    | |-----------+----------+---------+----------| | address 2 |   no     |  no     |   yes    | \-------------------------------------------/ 

i think achieve create table cars_addresses (id, car_id, address_id, available:bool)

but don't know how specify active record. questions are:

  • is right schema structure ?
  • how can implement through active record ?

what need has_and_belongs_to_many between cars , address. plenty of rubbyists relationship should never used (and has_many :through should used instead) perfect place can't think of additional information need stored between models. be:

user (id, name, email)   has_many :addresses   has_many :cars  car (id, name)   belongs_to :user   has_and_belongs_to_many :addresses  address (id, name, user_id)   belongs_to :user   has_and_belongs_to_many :cars 

then need create table addresses_cars (orders matters, no model needed) without id , 2 collumns: address_id , car_id. that's it! "magically" work:

user.cars.first.addresses => list of location car available user.addresses.first.cars => list of cars available under address user.addresses.first.cars << user.cars.first => add car given address 

Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -