ruby on rails - How to create association for nested model in a form -
in ruby on rails application want allow adding/editing of nested model has associated model.
model survey string title has_many questions model question string question belongs_to category model category string name
for sake of argument let's assume user should have enter new category when entering question (i couldn't come better example, sigh).
in model/survey/edit.html.erb have working setup adding questions , saving them. when added category
model picture, face problem when adding new question
, there no corresponding category
name-field displayed. suspect because though call question.new, not call question.category.build - , have no idea where/how that.
my edit.html.erb:
<h1>editing survey</h1> <%= render :partial => 'form' %>
my _form.html.erb:
<% form_for(@survey) |f| %> <%= f.error_messages %> <p> <%= f.label :title %><br /> <%= f.text_field :title %> </p> <div id="questions"> <% f.fields_for :questions |q| %> <%= render :partial => 'question', :locals => { :pf => q } %> <% end %> </div> <%= add_a_new_child_link("new question", f, :questions) %> <% end %>
my _question.html.erb:
<div class="question"> <%= pf.label :question %> <%= pf.text_field :question %> <% pf.fields_for :category |c| %> <p> <%= c.label :name, "category:" %> <%= c.text_field :name %> </p> <% end %> </div>
a quick fix situation use virtual attributes. eg, in question model:
def category_name=(new_name) if category category.name = new_name else category = category.new(:name => new_name) end end def category_name return category.name if category "" end
in _question, there no need use nested form. add like:
<%= pf.text_field :category_name %>
i didn't test it, caught ideea.
Comments
Post a Comment