如何创建视图的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
当我present的形式对于用户来说,这样他就可以创建一个新的车,我只想让他从可用引擎之一选择(可用的引擎将在选择
,人口由 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
据引擎
不是belongs_to的车
让你shoulduse嵌套属性在这里。这截屏将是非常有用的你:
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
- http://railscasts.com/episodes/196-nested-model-form-part-1
- http://railscasts.com/episodes/197-nested-model-form-part-2
结账API:<一href="http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for" rel="nofollow">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屋!