Reputation: 4091
I have 3 models: user, seller and cars
i want the user to be able to choose a car from a seller and this gets added to the user's shopping list.
I have something like this in my car controller:
@user = User.find(params[:user])
@seller = Seller.find(params[:seller])
@car = @user.cars.build(params[:car])
but the seller isnt being added. how can I do this please?
Btw I have this:
class Car < ActiveRecord::Base
belongs_to :user
belongs_to :seller
end
in my Model for car
Upvotes: 0
Views: 130
Reputation: 23450
If you ensure that the fields in your form that produce params[:car] includes a field for the seller's id you won't need to change your controller at all.
Eg:
<% fields_for :car, @seller.cars.build do |car_form| %>
<%= car_form.hidden_field :seller_id
... more fields for car form ...
<% end %>
Upvotes: 1
Reputation: 4580
add:
@car.seller = @seller
after you build the car. Then @car.save
Build doesn't know about @seller, you need to tell the car that it has a seller. It only really knows that there's a user because you created the car from the user.
You could also do:
@car = Car.new
@car.seller = @seller
@car.user = @user
Upvotes: 2