多选:附加一个额外的空ID

时间:2017-10-12 15:21:01

标签: ruby-on-rails ruby

当我想创建一本新书时,我需要将它附加到类别。但是当我试图保存一本新书时,我收到了错误:"找不到带有<的类别。 id" ="。 >我不知道为什么,但除了我已经附上的那些之外还有一个id附加。这个id是空的("")。   它看起来像这样("书" => {"名称" =>" 12"," category_ids" => [& #34;"," 2"," 7"],......)。请帮帮我。 我的bookcontroler:

def new 
 @book = Book.new(book_params)
end

def create 
 @book = Book.new(book_params)
 @category = Category.find(id: params[:ids])
 BookCategory.create!(book: @book, category: @category)
 @book.save
end

private

def book_params
 params.require(:book).permit(:name, :author, :image, :description)
end

我的表格:

    <%= form_for (@book) do |f| %>
      <%= f.collection_select :category_ids, Category.order(:name), :id, :name, {},{ multiple: :true } %><br>
    <% end %>

我的错误:enter image description here

1 个答案:

答案 0 :(得分:0)

如果您已正确设置关联:

class Book < ApplicationRecord
  has_many :book_categories
  has_many :categories, through: :book_categories
end

class Category < ApplicationRecord
  has_many :book_categories
  has_many :books, through: :book_categories
end

class BookCategory < ApplicationRecord
  belongs_to :book
  belongs_to :category
end

对于每个has_many关联,ActiveRecord会创建一个_ids setter和getter:

@book = Book.find(1)
@book.category_ids 
# => [1, 2, 3]
@book.category_ids = [2,4]  # will add 4 and remove 1 and 3.

因此您无需手动设置关联,只需传递category_ids参数:

def new 
 @book = Book.new # don't assign params in the new method!
end

def create 
  @book = Book.new(book_params)
  if @book.save
    redirect_to @book
  else
    render :new
  end
end

private

def book_params
  # category_ids: [] allows an array of scalar values
  params.require(:book)
        .permit(:name, :author, :image, :description, category_ids: [])
end

由于您使用的.find数组参数可能为零或为空,因此您的代码无效。

collection_select的options参数也是可选的:

<%= form_for (@book) do |f| %>
  <%= f.collection_select :category_ids, Category.order(:name), :id, :name, { multiple: :true } %><br>
<% end %>