2010-01-11 106 views
0

在我的Ruby on Rails应用程序中,我想允许添加/编辑本身具有关联模型的嵌套模型。如何在表单中为嵌套模型创建关联

model Survey 
    string title 
    has_many questions 

model Question 
    string question 
    belongs_to category 

model Category 
    string name 

对于参数的缘故,让我们假设用户应该始终有进入的问题(我不能想出一个更好的例子,叹气)当进入一个新的类别。

在我的模型/ survey/edit.html.erb中,我有一个工作设置用于添加问题并保存它们。但是,当我将Category模型添加到图片中时,现在我面临的问题是,添加新的Question时,没有显示相应的名称字段Category。我怀疑这是因为即使我调用Question.new,我也不会调用question.category.build - 我不知道在哪里/如何做。

我edit.html.erb:

<h1>Editing Survey</h1> 

<%= render :partial => 'form' %> 

我_form.html.erb:

<% form_for(@survey) do |f| %> 
    <%= f.error_messages %> 

    <p> 
    <%= f.label :title %><br /> 
    <%= f.text_field :title %> 
    </p> 

    <div id="questions"> 
    <% f.fields_for :questions do |q| %> 
     <%= render :partial => 'question', :locals => { :pf => q } %> 
    <% end %> 
    </div> 

    <%= add_a_new_child_link("New question", f, :questions) %> 
<% end %> 

我_question.html.erb:

<div class="question"> 
    <%= pf.label :question %> 
    <%= pf.text_field :question %> 

    <% pf.fields_for :category do |c| %> 
    <p> 
     <%= c.label :name, "Category:" %> 
     <%= c.text_field :name %> 
    </p> 
    <% end %> 
</div> 

回答

0

要快速解决你的情况是使用虚拟属性。 EG,在你的问题型号:

def category_name=(new_name) 
if category then 
    category.name = new_name 
else 
    category = Category.new(:name => new_name) 
end 
end 

def category_name 
    return category.name if category 
    "" 
end 

在你_question,也没有必要使用嵌套的表格。只需添加如下:

<%= pf.text_field :category_name %> 

我没有测试它,但你可能抓住了ideea。

+0

我实际上自己修复了这个问题,而不是Question.new,我只需要在将问题传递给JS生成器函数之前做一个question.category.build。但我真的很喜欢你的想法,会尽快给你一个尝试。 – Steve 2010-01-12 15:13:29