如何为 has_one 关联创建视图? [英] How do I create the view for the has_one association?
问题描述
所以,假设我有这个模型:
So, imagine I have this model:
class Car
has_one :engine
end
和引擎型号:
class Engine
belongs_to :car
end
当我向用户展示表单,以便他可以创建一辆新车时,我只想让他从可用引擎中选择一个(可用引擎将在 select
,由 collection_select
填充).问题是,如果我像这样构建字段:
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 %>
当我尝试保存它时,我会得到一个 AssociationTypeMismatch,说它需要一个引擎,但它收到了一个字符串.
When I will try to save it, I will get an AssociationTypeMismatch saying that it expected an Engine, but it received a string.
这是这样做的方式吗?
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
我一直觉得像将引擎与汽车相关联这样的事情是由 Rails 自动完成的,但我不知道如何让他做到.
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.
切换 has_one
和 belongs_to
关联是实现这一目标的唯一方法吗?
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.
推荐答案
你应该使用 engine_id
<%= f.collection_select :engine_id, Engine.all, :id, :name %>
UPD
至于 Engine
不属于 Car
,所以你应该在这里使用嵌套属性.此截屏视频对您非常有用:
as far as Engine
is not belongs_to Car
so you shoulduse Nested Attributes here. This screencast will be very useful for you:
- http://railscasts.com/episodes/196-nested-模型形式部分 1
- http://railscasts.com/episodes/197-nested-模型形式第 2 部分
结帐 API:http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for
简短介绍:
class Car
has_one :engine
accepts_nested_attributes_for :engine
end
并以您的形式:
<%= form_for @car ... do |f| %>
...
<%= f.fields_for :engine do |b| %>
<%= b.collection_select :id, Engine.all, :id, :name %>
...
<% end %>
...
<% end %>
这篇关于如何为 has_one 关联创建视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!