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

ビルドインコントローラーを設定する理由は 1 つありますか?

4

1 に答える 1

1

をビルドする場所を尋ねていると仮定するとfield_content_types、この特定のケースでは、モデルまたはコントローラーのどちらでビルドするかは問題ではないと思います。

経験則としては、コントローラーを薄く保ち、モデルを太くすることですが、ビルド方法はすでに非常に簡潔であるため、モデルからビルドしてもあまり得られません。

個人的には、コントローラーに組み込むだけです。

于 2013-07-16T17:55:04.127 に答える