开发者

How to create association for nested model in a form

开发者 https://www.devze.com 2022-12-16 05:49 出处:网络
In my Ruby on Rails application I want to allow the adding/editing of a nested model which itself has an associated model.

In my Ruby on Rails application I want to allow the adding/editing of a nested model which itself has an associated model.

model Survey
   string title
   has_many questions

model Question
   string question
   belongs_to category

model Category
   string name

For the sake of argument let's assume that the user should always have to enter a new category when entering a question (I couldn't come up with a better example, sigh).

In my model/survey/edit.html.erb I have a working setup for adding questions and saving them. However when I added the Category model to the picture, I now face the problem that when adding a new Question, there is no corresponding Category name-field displayed. I suspect this is because even though I do call Question.new, I do not call question.category.build - and I have no idea where/how to do that.

My edit.html.erb:

<h1>Editing Survey</h1>

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

My _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 %>
  开发者_如何学Go</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 do |c| %>
    <p>
      <%= c.label :name, "Category:" %>
      <%= c.text_field :name %>
    </p>
  <% end %>
</div>


A quick fix for your situation is to use virtual attributes. EG, in your Question model:

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

In your _question, there no need to use nested form. Just add something like:

<%= pf.text_field :category_name %>

I didn't test it, but you probably caught the ideea.

0

精彩评论

暂无评论...
验证码 换一张
取 消