mercredi 1 juillet 2020

Using checkboxes to pass multiple strings to array in migration with ruby

Im looking to have a user create a post where they specify what instruments they play. There should be a checkbox for each instrument so the user can select the ones that apply to the post. I was able to display the instruments and their checkboxes in the post creation but I cannot figure out how to save them to the post. I get error ActiveRecord::AssociationTypeMismatch.

Displaying all instruments and passing integers for each (Id like to pass strings)

  <% Instrument.all.each do |instrument| %>
    <%= check_box_tag "post[instruments][]", instrument.id %>
    <%= instrument.name %> <br>
  <% end %>

  <div class="actions">
    <%= form.submit %>
  </div> 

Migration to receive array of integers

class AddTagsToPost < ActiveRecord::Migration[5.2]
  def change
    add_column :posts, :instruments, :integer, array: true, :default => []
  end
end

schema.rb

 create_table "instruments", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "posts", force: :cascade do |t|
    t.bigint "category_id"
    t.string "title"
    t.text "content"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "account_id"
    t.integer "instruments", default: [], array: true
    t.index ["account_id"], name: "index_posts_on_account_id"
    t.index ["category_id"], name: "index_posts_on_category_id"
  end

post.rb model

class Post < ApplicationRecord
  belongs_to :category
  belongs_to :account
  has_many :instruments
  validates :title, presence: true, length: { minimum: 3 }
  validates :content, presence: true, length: { maximum: 500 }

end

instrument.rb model

class Instrument < ApplicationRecord
  belongs_to :posts, optional: true
end



Aucun commentaire:

Enregistrer un commentaire