mardi 27 décembre 2016

rails : create children for given parent_id

i need your help to create parent-child relation.

i have a problem to make the create of the child working fine.

this is the model:

class Nccheklist < ActiveRecord::Base
  has_many :children, class_name: "Nccheklist", foreign_key: "parent_id"
  belongs_to :parent, class_name: "Nccheklist"

  def has_parent?
    parent.present?
  end

  def has_children?
    children.exists?
  end


end

the controller:

def create
    @nccheklist = Nccheklist.new(nccheklist_params)
    if @nccheklist.save
      redirect_to nccheklists_url, notice: 'Nccheklist was successfully created.'
    else
      render :new
    end
  end

and the view :

<%= form_for(@nccheklist) do |f| %>
  <% if @nccheklist.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@nccheklist.errors.count, "error") %> prohibited this nccheklist from being saved:</h2>

      <ul>
      <% @nccheklist.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
<div>
  <%= f.collection_select(:parent_id, @rootcat, :id, :name) %>
</div>
<br/><br/>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

when i submit the form, parent_id always equal null on database !

can someone help me please.

thanks.

Aucun commentaire:

Enregistrer un commentaire