Carpela
Carpela

Reputation: 2195

has_many nested form with has_one inside

I'm having a similar issue to has_many nested form with a has_one nested form within it

Basically trying to create tasks at the same time I'm creating a client, some of those tasks may be recurring which is handled through a has_one relationship to a recurring model.

So.

Client Model

    attr_accessible :tasks_attributes
    has_many :tasks, dependent: :destroy
    accepts_nested_attributes_for :tasks, :allow_destroy => true, :reject_if => lambda { |t| t['task_type'].blank? }

Task model

     belongs_to :client
     has_one :recurring, :dependent => :destroy
     accepts_nested_attributes_for :recurring, :reject_if => lambda { |t| t['recurring_type'].blank? }
     attr_accessible :recurring_attributes

Clients_controller

def new
@client = Client.new 
@task = @client.tasks.build

Client/_form

    <table id="tasks" class="table table-striped">
      <%=f.simple_fields_for :tasks, :wrapper => false  do |task|%>
        <tr class="fields>
                <td><%=task.input :task_type, :label => "Task Type", :collection => Task::TASK_TYPES %></td>
                <td>
                  <%= task.simple_fields_for :recurring, @task.build_recurring do |recur|%>
                    <%= recur.input :recurring_type, :as => :select, :collection => Recurring::RECUR_TYPES %>
                  <%end%>
                </td>
                <td><%= task.input :due_date, :as => :datepicker, :label => "Next Due Date"%></td>
                <td><%= task.link_to_remove "Remove this task" %></td>
            <%end%>
        </tr>
        </table>
        <%= f.link_to_add "Add a task", :tasks, :data => { :target => "#tasks" } %>

I can get the form to display correctly and it now adds and removes tasks correctly. But when I submit I get a

    undefined method `build_recurring' for nil:NilClass

I'm now on the 5th attempt at doing this in different ways and it's driving me insane.

Any ideas what I'm doing wrong?

Upvotes: 1

Views: 267

Answers (1)

Dev R
Dev R

Reputation: 1902

The issue is coming because of reject_if. It is rejecting the blank fields which when error comes and because of this that field is not showing up.

Removing reject_if for blank can be changed to nil, and after that validation can be handled as regular validation as handled.

Upvotes: 1

Related Questions