1
我试图在单个表单上显示我的用户和个人档案模型时试图让* fields_for *产生输出时遇到了一些麻烦,这些使用* has_one *和* belongs_to *关系。当使用一对一关系时没有通过fields_for输出
因此,这里的提取物形成的模型类的顶部:
class User < ActiveRecord::Base
has_one :profile
accepts_nested_attributes_for :profile
class Profile < ActiveRecord::Base
belongs_to :user
控制器是非常简单的标准:
def new
@user = User.new
end
def edit
@user = User.find(params[:id])
end
这里是一个片段出来的观点,因为它目前站:
<%= form_for(@user) do |f| %>
<% f.fields_for :profile do |profile_form| %>
<div class="field">
<%= profile_form.label :name %><br />
<%= profile_form.text_field :name %>
</div>
<% end %>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我试过其他的东西,像这样:
<% fields_for @user.profile do |profile_form| %>
,一切工作正常,如果我手动添加字段:
<div class="field">
<label for="user_name">Name</label><br>
<input id="user_name" name="user[profile_attributes][name]" size="30" type="text" value="<%= @user.profile.name %>">
</div>
值得一提的是,我是相当新的轨道,并不能完全确定这些功能的引擎盖下是如何工作的,虽然我已经阅读documentation和guide。同样在我的搜索中,有很多fields_for一对多关系的例子,所以我可能会以错误的方式解决这个问题?
所有帮助,建议和进一步阅读非常感谢:-)
干杯,
山姆
我知道这会很简单 - 非常感谢:-) 我只从第3版开始使用rails,搜索时可能很难查看版本之间的差异,虽然这样的东西可以轻松跳过。任何值得阅读的相关内容? – 2011-03-22 10:33:29
不是。如果他们使用了ERB块('do%> ... <%end'),那么助手在Rails 2中编写代码是一件痛苦的事情(虽然内存效率更高)。在Rails 3中,他们决定让所有事情都像一个简单的字符串一样工作。因此,如果您忘记添加'=',则不会打印该字符串。但是来自Rails 2次的许多例子都不会有'=' - 一个警告。 – 2011-03-22 10:45:03
我一直在努力让这个工作2个小时。你完全用这个保存了我的培根 - 只是希望我早点谷歌搜索!非常感谢! – 2011-10-20 00:03:06