最佳做法的嵌套属性

问题描述 投票:1回答:1

我有一个模型具有另一个嵌套的属性。

我的问题是:如何更好地调用控制器或模型的内置解决方案?

看到那个模型:

class ContentType < ActiveRecord::Base
  after_initialize :add_fields
  belongs_to :project
  has_many :field_content_types

  accepts_nested_attributes_for :field_content_types, reject_if: proc {|attributes| attributes['name'].blank?}

  private

  def add_fields
    self.field_content_types.build if new_record?
  end
end

在模型中删除after_initialize并在控制器中添加行

class ContentTypesController < ApplicationController
  def new
    @content_type = ContentType.new
    @content_type.field_content_types.build
  end
end

有一个理由来设置内置控制器?

ruby-on-rails activerecord nested-attributes has-many
1个回答
1
投票

假设您在询问应该在哪里构建field_content_types ,在这种特殊情况下,我认为无论是在模型还是在控制器中构建都没有关系。

经验法则是使控制器变薄且模型肥大 ,但是构建方法已经如此简洁,以至于从模型构建它不会带来太多好处。

就个人而言,我只是将其构建在控制器中。

© www.soinside.com 2019 - 2024. All rights reserved.