1

Product、Category、および Categorization という 3 つのモデルがあります。

製品モデル:

    attr_accessible :title, :description, :price, :image_url
    has_many :categorizations
    has_many :categories, :through => :categorizations

カテゴリ モデル:

    attr_accessible :name
    has_many :categorizations
    as_many :products, :through => :categorizations

分類モデル:

    attr_accessible :category_id, :product_id
    belongs_to :category
    belongs_to :product

製品モデルを作成するときに分類オブジェクトを作成するにはどうすればよいですか? 新しい商品フォームにカテゴリーセレクトを追加しました。

基本的に、新しい製品オブジェクトを作成するときに、product_id と選択した category_id をプッシュして新しい分類オブジェクトを作成し、製品をカテゴリに関連付けることができるようにします。

新製品の _form.html:

    <div>
        <%= f.label :title %>:<br />
        <%= f.text_field :title %><br />
      </div>
      <div>
        <%= f.label :description %>:<br />
        <%= f.text_area :description, :rows => 6 %>
      </div>
      <div>
        <%= f.label :price %>:<br />
        <%= f.text_field :price %><br />
      </div>
      <div>
        <%= f.label :image_url %>:<br />
        <%= f.text_field :image_url %><br />
      </div>

      <% @categories.each do |category| %>

      <div>
        <% f.fields_for :categorization do |builder| %>
        <%= render 'categorization_fields', :f => builder, :product => @product,         :category => category %>
      </div>
      <% end %>
      <% end %>

製品コントローラ:

    def index
        @products = Product.all
      end

      def new
        @category = Category.all
        @product = Product.new
        @categories = @category.find(params[:category])
        categorization = @product.categorizations.build
      end

      def create
        @product = Product.new(params[:product])
        if @product.save
          redirect_to products_path
        else
          render :new
        end
      end

      def edit
        @product = Product.find(params[:id])
      end

      def update
        @product = Product.find(params[:id])
        if @product.update_attributes(params[:product])
          redirect_to @product
        else
          render :edit
        end
      end

      def show
        @product = Product.find(params[:id])
      end

      def destroy
        @product = Product.find(params[:id])
        @product.destroy
        redirect_to products_path
      end

    end

製品モデルのaccepts_nested_attributes_forでこのように動作させることはできません。

どんな助けでも大歓迎です。

4

1 に答える 1

0

たぶん、あなたはautosaveあなたの望む関係にオプションを追加する必要があります、例えば:

has_many :categorizations, :autosave => true
accepts_nested_attributes_for :categorizations

これによりautosave、リレーションを宣言したモデルを保存するときに'dリレーションが保存されます。

于 2012-12-05T13:21:40.790 に答える