Sunday, August 5, 2012

[Rails] Re: Rails associations

It sounds like you're running up against database foreign key constraints: your model needs to have those id attributes filled in before you can save it. (This is often caught with validations at the rails application layer too, with `validates :vehicle_type, presence: true`)

This is one possible approach:

business = Business.first
car = VehicleType.find_by_name("car")

first_vehicle = Vehicle.new
first_vehicle.business = business
first_vehicle.vehicle_type = car
first_vehicle.save

Or another way:

first_vehicle = Vehicle.create do |v|
  v.business = business
  v.vehicle_type = car
end

Or:

first_vehicle = business.vehicles.build(vehicle_type: car)
first_vehicle.save

Or again:

first_vehicle = business.vehicles.create(vehicle_type: car)

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/yv0vU9susn4J.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate