So, imagine I have this model:
class Car
has_one :engine
end
and the engine model:
class Engine
belongs_to :car
end
When I present the form for the user, so that he can create a new car, I only want to allow him to select from one of the available engines ( the available engines will be in a select
, populated by the collection_select
). The thing is, if I build the field like this:
<%= f.collection_select :engine,Engine.all,:id,:name %>
When I will try to save it, I will get an AssociationTypeMismatch saying that it expected an Engine, but it received a string.
Is this the way to do it?
def create
car = Car.new(params[:car])
engine = Engine.find(params[:engine])
car.engine = engine
if car.save
# redirect somewhere
else
# do something with the errors
end
end
I always felt that stuff, like associating an engine to a car, are done automatically by Rails, but I don't know how to make him do it.
Is switching the has_one
and belongs_to
associations the only way to achieve this?
I am lost and I feel like I'm missing something very basic here.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…