Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
646 views
in Technique[技术] by (71.8m points)

ruby on rails - How do I create the view for the has_one association?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use engine_id

<%= f.collection_select :engine_id, Engine.all, :id, :name %>

UPD

as far as Engine is not belongs_to Car so you shoulduse Nested Attributes here. This screencast will be very useful for you:

Checkout api: http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for

Short intro:

class Car
  has_one :engine
  accepts_nested_attributes_for :engine
end

and in your form:

<%= form_for @car ... do |f| %>
  ...
  <%= f.fields_for :engine do |b| %>
    <%= b.collection_select :id, Engine.all, :id, :name %>
    ...
  <% end %>
  ...
<% end %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...