Rails 4 HABTM不保存

时间:2014-01-06 12:13:01

标签: ruby-on-rails ruby-on-rails-4 haml simple-form

我正在尝试从我的Product模型中保存HABTM关系,但它似乎根本没有保存。

以下是我的Products控制器:

# POST /products
  # POST /products.json
  def create
    @product = Product.new(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
        format.json { render action: 'show', status: :created, location: @product }
      else
        format.html { render action: 'new' }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

以下是我的模特:

class Product < ActiveRecord::Base
    resourcify

  belongs_to :user
  has_and_belongs_to_many :tags
  has_and_belongs_to_many :booths

  has_one :uploaded_file, as: :imageable, dependent: :destroy
  accepts_nested_attributes_for :uploaded_file

  validates :name, :description, presence: true
  validates :user, associated: true, presence: true
  # validates :product_url, url: true, presence: false
end

这是我使用simple_form和HAML创建的表单:

= simple_form_for(@product, :html => { :class => "form-horizontal" }, :wrapper => "horizontal", defaults: { :input_html => { class: "form-control"}, label_html: { class: "col-lg-4" } } ) do |f|
  = f.error_notification

  .form-inputs
    = f.input :name
    = f.input :description
    = f.input :product_url
    = f.fields_for :uploaded_file do |uploaded_files|
      = uploaded_files.label :assets, "Product image", :class => "col-lg-4 control-label"
      .col-lg-8
        .fileinput.fileinput-new{"data-provides" => "fileinput"}
          .fileinput-preview.thumbnail{"data-trigger" => "fileinput", "style" => "width:200px; height:150px;"}
            -if @product_logo_url.present?
              %img{ :src => @product_logo_url }
          %div
            %span.btn.btn-default.btn-file
              %span.fileinput-new Select image
              %span.fileinput-exists Change
              = uploaded_files.file_field :assets
            %a.btn.btn-default.fileinput-exists{:href => "#", "data-dismiss" => "fileinput"} Remove
    = f.input :request_info
    = f.input :email_notification
    = f.input :emails
    = f.hidden_field :user_id, :value => current_user.id
    = f.association :booths, input_html: {class: "chosen"}

  .form-actions
    = f.button :submit, class: "btn btn-primary"

我的HABTM表是:

table name - booths_products
integer - booth_id
integer - product_id

我还检查了产品控制器下的强参数:

def product_params
      params.require(:product).permit(:name, :description, :product_url, :image_id, :request_info, 
        :email_notification, :emails, :user_id, :booth_ids, uploaded_file_attributes: [:assets])
    end

我理解booth_ids将保存HABTM表的所有记录。

另外需要注意的是,当我检查表单提交的params时,booth_ids字段中的第一个是空的,所以它就像例如:

 params[:product][:booth_ids]['', 2]

这里有什么问题我需要修理才能妥善保存吗?

0 个答案:

没有答案