dimanche 12 avril 2015

Rails 4: Being able to select multiple instances of one model when creating the model it has a has_many :through relationship with

When I add a new Book to my Library, I want to be able to specify what Shelves in that Library it should belong to. Right now, I'm able to add a Book to my Library, but I'm having issues with the Shelves. I'm pretty new at learning Rails and I'd appreciate any help.


Models


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


shelf.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


Controller


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


View


_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 %>

Aucun commentaire:

Enregistrer un commentaire