当我向其中添加新项Book
时Library
,我希望能够指定什么Shelves
(注意: “ Shelf
”是我在应用程序中用于模型的术语,该模型Books
在一个分组内Library
;该模型的更好名称应该是Category
或Genre
,但是我很愚蠢),因为Library
它应该属于。现在,我能够将添加Book
到我的Library
,但我在使用的问题Shelves
。我是学习Rails的新手,我将不胜感激。
楷模
user.rb:
class User < ActiveRecord::Base
has_one :library, dependent: :destroy
...
end
library.rb:
class Library < ActiveRecord::Base
belongs_to :user
has_many :shelves, dependent: :destroy
has_many :catalogs, dependent: :destroy
has_many :books, :through => :catalogs, dependent: :destroy
...
end
book.rb:
class Book < ActiveRecord::Base
has_many :catalogs, dependent: :destroy
has_many :libraries, :through => :catalogs, dependent: :destroy
has_many :bookshelves, dependent: :destroy
has_many :shelves, :through => :bookshelves, dependent: :destroy
...
end
catalog.rb:
class Catalog < ActiveRecord::Base
belongs_to :book
belongs_to :library
end
rack.rb:
class Shelf < ActiveRecord::Base
belongs_to :library
has_many :bookshelves, dependent: :destroy
has_many :books, :through => :bookshelves, dependent: :destroy
...
end
bookshelf.rb
class Bookshelf < ActiveRecord::Base
belongs_to :book
belongs_to :shelf
end
控制器
books_controller.rb
class BooksController < ApplicationController
...
def create
@book = Book.new(book_params)
@library = current_user.library
if @book.save
@book.catalogs.create(:library_id => @library.id)
flash[:success] = "Book added to library!"
redirect_to current_user
else
render 'current_user'
end
end
...
private
def book_params
params.require(:book).permit(:title, :author, :publisher, :isbn)
end
...
end
看法
_book_form.html.erb:
<%= form_for(@book) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_field :title, placeholder: "Book Title" %>
<%= f.text_field :author, placeholder: "Author" %>
<%= f.text_field :publisher, placeholder: "Publisher" %>
<%= f.text_field :isbn, placeholder: "ISBN" %>
<%= f.fields_for :catalogs do |ff| %>
<%= ff.hidden_field :library_id %>
<% end %>
<%= f.fields_for :bookshelves do |ff| %>
<%= ff.collection_select :shelf_ids, current_user.library.shelves.all.collect {|x| [x.name, x.id]}, {}, multiple: true %>
<% end %>
</div>
<%= f.submit "Add Book to Library", class: "btn btn-primary" %>
<% end %>
在您的book_params
方法中,您没有shelf_ids
列出。因此,它将不会传递到.new
方法中,因此不会被保存。由于您ids
不需要多个,所以您想这样做:
def book_params
params.require(:book).permit(:title, :author, :publisher, :isbn, shelf_ids: [])
end
这样,控制器就知道它是一个数组,而不仅仅是一个值。
哦,顺便说一句,shelf_ids
其他类似的数组值必须在末尾,否则将引发错误。
编辑:
还要更改这部分代码:
<%= f.fields_for :bookshelves do |ff| %>
<%= ff.collection_select :shelf_ids, current_user.library.shelves.all.collect {|x| [x.name, x.id]}, {}, multiple: true %>
<% end %>
对此:
<%= f.collection_select :shelf_ids, current_user.library.shelves.all.collect {|x| [x.name, x.id]}, {}, multiple: true %>
您无需担心through
关联的一部分。只需设置has_many
零件即可使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句