嵌套属性问题的表单和视图

时间:2014-09-04 11:52:20

标签: ruby-on-rails ruby ruby-on-rails-4 simple-form nested-attributes

我已经检查了有关如何创建嵌套属性表单的主题,但无法使其正常工作。

我有两种模式:

class LogFile < ActiveRecord::Base
  has_one :ConfigFile
  accepts_nested_attributes_for :ConfigFile, allow_destroy: true
end

class ConfigFiles < ActiveRecord::Base
  belongs_to :LogFile
end

在我logfile的控制器中:

 def log_file_params
      params.require(:log_file).permit(:name,
                                       ...,
                                       :config_file_id,
                                       config_files_attributes: [:id, :json, :_destroy])
 end

表格如下:

  <%= f.simple_fields_for :config_file do |n| %>
      <%= n.input :json %>
  <% end %>

我需要填充config_file_id模型的log_file字段,以便能够获取特定日志文件的配置文件。

我尝试将config_files_attributes更改为config_file_attributes。另外,ti改变了

<%= f.simple_fields_for :config_file do |n| %>

 <%= f.simple_fields_for :config_file_attributes do |n| %>
 <%= f.simple_fields_for :config_files_attributes do |n| %>

但似乎我无法在config_files表中创建记录(它始终为空)。

有谁能说出我做错了什么?


我修复了camel case语法并在log_file_id表中添加了config_file列。 我还无法填充nested表。

这是_form

<%= f.simple_fields_for :config_file_attributes do |n| %>
          <%= n.input :json %>
      <% end %>

这是controller

# Never trust parameters from the scary internet, only allow the white list through.
    def log_file_params
      params.require(:log_file).permit(:name,
                                       :description,
                                       :log_file,
                                       :access_type_id,
                                       :config_file_id,
                                       config_file_attributes: [:id, :json, :_destroy])
    end

这是调试输出(请注意,没有传递有关config_file的信息):

--- !ruby/object:LogFile
attributes:
  id: 2
  name: Tetsd2
  description: '123'
  created_at: 2014-09-04 09:34:48.141041000 Z
  updated_at: 2014-09-04 14:08:20.652419000 Z
  log_file: test.txt
  access_type_id: 2
  config_file_id: 

2 个答案:

答案 0 :(得分:2)

作为数据库转换,belongs_to应保留引用列,因此请尝试在log_id表中添加ConfigFiles来解决您的问题。 Rails在嵌套属性中也是如此。我已经为has_many协会尝试了它。

此外,你还没有指定has_one并且属于camel case。所以也要正确。也在accept_nested_attributes_for。

答案 1 :(得分:1)

传递给关联方法的符号是错误的:

belongs_to :LogFile

这应该是:

belongs_to :log_file

注意骆驼套管。

同样,以下内容也是错误的:

class LogFile < ActiveRecord::Base
  has_one :ConfigFile
  accepts_nested_attributes_for :ConfigFile, allow_destroy: true
end

应该是:

  has_one :config_file
  accepts_nested_attributes_for :config_file, allow_destroy: true

我认为你的strong_parameters电话错误了:

  params.require(:log_file).permit(:name,
    # ...
    config_files_attributes: []

由于LogFile只有一个ConfigFile,因此您应该删除s。它应该是config_file_attributes而不是config_files_attributes

相关问题