【问题标题】:Rails 5.0.5 - Data not saving using Ancestry GemRails 5.0.5 - 使用 Ancestry Gem 不保存数据
【发布时间】:2017-08-27 06:09:19
【问题描述】:

我正在使用Ancestry Gem 为我的页面模型构建一棵树。页面保存,但字段数据不保存到数据库。我没有看到任何错误,而且由于我是 Rails 新手,我不知道如何调试。下面是我的代码。谢谢。

页面模型

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

  has_ancestry
end

页面控制器 - 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>
...

【问题讨论】:

  • attr_accessor 不会将您的属性映射到数据库,这就是数据不会持久化的方式。您可以使用迁移将列添加到数据库中。 guides.rubyonrails.org/…
  • 我将祖先添加到我搭建并迁移的模型中。你指的是别的东西吗?

标签: ruby-on-rails ruby-on-rails-5 ancestry


【解决方案1】:

因为你使用 rails 5.0.5 那么你必须使用 strong 参数来允许保存字段而不是 attr_accessor :parent_id, :content, :title 您应该删除 attr_accessor 并在下面添加我的示例代码(您可以添加其他字段,但请确保您为祖先 gem 添加了 parent_id) 有关强参数的更多信息,您可以查看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

为祖先字段编辑

作为您的信息中的信息,您已添加脚手架 parent_id 字段,请尝试检查它并在下面查看添加 parent_id 的参考步骤

  • rails 生成迁移 add_ancestry_to_pages ancestry:string
  • 打开您的迁移文件并检查以下字段

db/migrate 文件夹中的迁移文件

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

为您的观点编辑

请使用 select,而不是使用集合选择,您可以检查它this link,因为 collection_select 输出是一个数组,并且与仅接收一个父级的祖先的 parent_id 不匹配

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

为访问父级编辑

如果您想从祖先的子记录中访问父级,您可以使用 object.parent.column_name 访问它,考虑您的 column_name 是名称,那么您可以使用 ,更多信息请至navigate your record here is link that you need

【讨论】:

  • 尝试了你的建议,除了:parent_id之外,所有字段都保留了
  • 请在 f.select 的底部查看我编辑的答案(作为 collection_select 的替代品
  • 我已经创建了列和索引,但我更新了我的选择字段,但数据仍然没有保留。但是,当我从我的参数定义中删除 private 时,它起作用了!!最后一个问题,现在我的 index.html.erb 文件中有&lt;td&gt;&lt;%= page.parent_id %&gt;&lt;/td&gt;,它显示了父级的id,但是我怎样才能获取父级ID 的字符串name
  • 我为你的最后一个问题添加了信息,请参阅为访问父编辑的部分
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 2014-11-22
相关资源
最近更新 更多