Charles Smith
Charles Smith

Reputation: 3289

Rails 5.0.5 - Data not saving using Ancestry Gem

I am using the Ancestry Gem to build a tree for my Page model. The page saves but the field data is not saved to the database. I am seeing no errors and since I am new to Rails, I am not sure how to debug. Below is my code. Thank you.

Page Model

class Page < ApplicationRecord
  attr_accessor :parent_id, :content, :title

  has_ancestry
end

Page Controller - def create

def create
    @page = Page.new(page_params)

    respond_to do |format|
      if @page.save
        format.html { redirect_to @page, notice: 'Page was successfully created.' }
        format.json { render :show, status: :created, location: @page }
      else
        format.html { render :new }
        format.json { render json: @page.errors, status: :unprocessable_entity }
      end
    end
  end

_form.html.erb

...
<div class="field">
  <%= f.label :parent_id %>
  <%= f.collection_select :parent_id, Page.order(:title), :id, :title, include_blank: true %>
</div>
...

Upvotes: 0

Views: 381

Answers (1)

widjajayd
widjajayd

Reputation: 6253

since you using rails 5.0.5 then you must use strong parameter to allow field to be saved not attr_accessor :parent_id, :content, :title you should delete attr_accessor and add my sample code below (you can add others field but make sure you added parent_id for ancestry gem) for more info about strong parameter you can check strong parameter rails

page_controller

class PagesController < ApplicationController

# your create method here

private

    def page_params
      params.require(:page).permit(
        :title,
        :your_other_field,
        :parent_id)
    end

end

edited for ancestry field

as information from your info you have added scaffold parent_id field, try to check it and below for your reference step to add parent_id

  • rails generate migration add_ancestry_to_pages ancestry:string
  • open your migration file and check the field as follow

migration file inside folder db/migrate

  class AddAncestryTopages < ActiveRecord::Migration
    def change
      add_column :pages, :ancestry, :string
      add_index  :pages, :ancestry
    end
  end
  • run rake db:migrate

edited for your view

instead using collection select please use select, you may check it this link since collection_select output is an array and is not match with parent_id for ancestry that just receive one parent

<%= f.select :parent_id, Page.order(:title).collect {|p| [ p.title, p.id ] }, { include_blank: true } %>

edited for access parent

if you would like to access parent from child record in ancestry you can access it with object.parent.column_name consider your column_name is name then you you can access the title of the parent page with <%= page.parent.name %>, for more info to navigate your record here is link that you need

Upvotes: 1

Related Questions