开发者

Problem using nested_form gem when save data

It's my first time here, and first time I use nested_form gem. Everything seemed to be ok, but the data from my "parent" model doesn't save.

Here is my code

    <%= nested_form_for @project do |f| %开发者_JAVA技巧>
      <p>
        <%= f.label :name %><br />
        <%= f.text_field :name %>
      </p> 

      <%= f.fields_for :tasks %>
      <p><%= f.link_to_add "Add a task", :tasks %></p>

      <%= f.submit %>
    <% end %>

so, when I "submit", just the tasks are saved ok, but not the project name.

Any clue for me? did I miss something??


You need to add the attribute. eg name to attr_accessible.

# app/models/project.rb
class Project < ActiveRecord::Base
  has_many :tasks, :dependent => :destroy
  accepts_nested_attributes_for :tasks, :allow_destroy => true
  attr_accessible :name,:tasks_attributes ## <-- you need this line
end


Your fields_for declaration isn't quite right

<%= f.fields_for :tasks %>

Should be

<%= f.fields_for :tasks do |task_builder| %>

you are also missing an end for that declaration and a render to render the partial that has the nested fields for the associated object.

So you should end up with something like this

<%= f.fields_for :tasks do |task_builder| %>
  <%= render 'task_fields', :f => task_builder %>
<% end %>
<p><%= f.link_to_add "Add a task", :tasks %></p>

That should do the trick. all you need to do now is create a _task_field.html.erb partial and add the task fields to it in the usual way using f.label, f.text_field etc...

p.s.

Your code could not possibly have ever worked. You would have had errors so something is probably missing from your opening post.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜