Saturday, 4 August 2018

How to use Selectize.js to find or create a rails belongs_to association?

I'm having a hard time figuring out how to combine Selectize.js with a belongs_to association in rails. I want to do something like this photo:

enter image description here

I've attempted using accepts_nested_attributes, but that doesn't seem to work with a belongs_to relationship.

I tried doing an auto-complete association like this railscast episode.

What I'd really like to do is use a Selectize style collection select to create the "Speaker" association if it's already in the database, but add a new one if it doesn't yet exist. Selectize enables me to add a new one, but I'm having trouble passing that through the form to create the new record in the associated model.

Here are my models:

class Quote < ApplicationRecord
  belongs_to :speaker,  class_name: "Artist"
  belongs_to :topic,    class_name: "Artist"
end

Quote.rb

class Artist < ApplicationRecord
  has_many :spoken_quotes, class_name: "Quote", foreign_key: :speaker_id
  has_many :topic_quotes,  class_name: "Quote", foreign_key: :topic_id
end

Artist.rb

And my form:

<%= f.label :speaker, 'Who said it?' %>
<%= f.collection_select :speaker_id, Artist.order(:name), :id, :name, {prompt: 'Select an artist'}, {class: 'form-control select-artist'} %>

_form.html.erb

Controllers:

quotes_controller.rb

artists_controller.rb

How can I create a new Artist (as "Speaker") through the Quote.new form through the Selective-style collection select? The Selectize behavior is the user experience I'm looking for, I just can't figure out how to create the new Artist through the Quote form.



from How to use Selectize.js to find or create a rails belongs_to association?

No comments:

Post a Comment