1

I got this model:

class Book < ActiveRecord::Base
    mount_uploader :image, ImageUploader
    belongs_to :editor
    belongs_to :catalog
    has_many :catalogs
end

_form.html.erb:

<div class="field">
    <%= f.label :catalog_id %><br>
    <%= f.collection_select(:catalog_id, @catalogs, :id, :ano, {:prompt => "Segure CTRL para seleção múltipla"}, {:multiple => true}) %>
</div>

controller:

params.require(:book).permit(:title, :format, :npag, :isbn, :sinopse, :image, :catalog_ids => [])

I can create new books but in the show.html.erb doesn't appear the selected itens, what is wrong?

I didn't change the show:

<%= @book.catalog %>
  • 1
    Please add the show.erb – acacia Oct 06 '14 at 17:42
  • Did you check if 'catalogs' has valid content at create? Put a raise @catalogs.inspect and check if there is anything there. – Laerte Oct 06 '14 at 18:06
  • Yes, it has valid content (#, #]>) – user3280355 Oct 06 '14 at 18:16
  • @user3280355 It should be <%= @book.catalogs %> and remove `belongs_to :catalog` line in your model – anusha Oct 06 '14 at 18:24
  • Here is what is happening: # I'm researching a solution using map, is that right? I want that appears the catalog year – user3280355 Oct 06 '14 at 19:32
  • when you say: `belongs_to :catalog` in `Book` model then your `books` table is expected to have `catalog_id`. In case of `has_many :catalogs` catalogs` table will have `book_id`. So, in order to your show code: `<%= @book.catalog %>` you must have a valid value of `catalog_id`. For example: `@book.catalog = @book.catalogs.first` will set the first catalog as the book's catalog. But, it won't make any sense. It's better you remove `belongs_to :catalog` as anusha suggested. – Surya Oct 06 '14 at 20:32
  • I found some explanation about relationships here that helps: http://stackoverflow.com/questions/4394803/rails-model-belongs-to-many. thanks to all. – user3280355 Oct 07 '14 at 18:43

2 Answers2

0

You should access each object to print its content:

<% @book.catalogs.each do |c| %>
<%= c.year %>
<% end %>
Laerte
  • 7,013
  • 3
  • 32
  • 50
  • Hm, i got this: SQLite3::SQLException: no such column: catalogs.book_id: SELECT "catalogs".* FROM "catalogs" WHERE "catalogs"."book_id" = ? – user3280355 Oct 07 '14 at 18:07
  • Which kind of relation are you trying to do? Book 1 - N Catalogs, Books N - 1 Catalog, or Books N - N Catalogs? – Laerte Oct 08 '14 at 13:43
0
<%= f.collection_select(:catalog_id, @catalogs, :id, :ano, {:prompt => "Segure CTRL para seleção múltipla", :selected => @catalogs.pluck(:id)}, {:multiple => true}) %>

You have to pass the selected option... .pluck will return an array of just ids of the catalogs... this relies on your show (and edit for that matter) method having @catalogs = @book.catalogs.

Dudo
  • 4,002
  • 8
  • 32
  • 57