Has_many和belongs_to嵌套表单

时间:2016-07-04 06:59:05

标签: ruby-on-rails ruby-on-rails-4 nested-forms

我需要将beauty_type_id的值以beauty_type形式放入嵌套表单格式的产品中。它无法创建和更新beauty_type表。我的表单或控制器有问题,所以在保存和更新beauty_type时它会继续回滚。

class BeautyType < ActiveRecord::Base
has_many :products
accepts_nested_attributes_for :products
end

class Product < ActiveRecord::Base
belongs_to :beauty_type
end

create_table "products", force: :cascade do |t|
t.integer  "beauty_type_id"
end

class BeautyTypeController < ApplicationController
def new
    @beauty_type = BeautyType.new
    @beauty_type.products.build
end
def create
    @beauty_type = BeautyType.new(beauty_type_params)
    @beauty_type.save
end
private
    def beauty_type_params
      params.require(:beauty_type).permit(:title, :story, :image, :published_at, :meta_description, :meta_title, products_attributes: [:beauty_type_id, :id])

    end
    end

form:
<%= form_for(@beauty_type, :url => path, html: { class: "form-horizontal", role: "form" }) do |f| %>
....
<div class="form-group row">
    <%= f.fields_for :products, @beauty_type.products do |builder| %>
      <div class='nested-fields row'>
       <%= builder.label :id, 'Product', class: "col-md-2 control-label" %>
       <div class="col-md-10">
        <%= builder.select :id, Product.all.collect {|x| [x.name, x.id]}, prompt: "Select something", class: "select2" %>
       <%= link_to_remove_association "remove task", builder %>
       </div>
      </div>
      <div class="col-md-11 right">
        <%= link_to_add_association 'add task', builder, :products %>
      </div>
    <% end %>

0 个答案:

没有答案