Jquery Token Input with has_many association and join table.?

35 views Asked by At

I have 3 models

class Store < ActiveRecord::Base

 has_many :storedescriptions 
 has_many :descriptions , through: :storedescriptions



 def self.tokens(query)
  stores = where("name like ?", "%#{query}%")
    if stores.empty?
        [{id: "<<<#{query}>>>", name: "New: \"#{query}\"" }]
    else
        stores
    end
 end

 def self.ids_from_tokens(tokens)
  tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
  tokens.split(',')
 end

end

Description Model

class Description < ActiveRecord::Base
 has_many :storedescriptions 
 has_many :stores , through: :storedescriptions
end

and storedescription model

class Storedescription < ActiveRecord::Base
belongs_to :user
belongs_to :store
belongs_to :description

 attr_reader  :store_tokens


 def store_tokens=(tokens)
    Store.ids_from_tokens(tokens)
 end   
end

I have a form for storedescription

<%= simple_form_for(@storedescription) do |f| %>
                    <%= f.error_notification %>

                    <div class="form-inputs">
                        <%= f.input :store_tokens,:label => "Add Store Name", input_html: { class: 'priceaddtokendesc form-control'} %>

                        <%= f.input :description_id, :as => "hidden",:input_html => { :value => item.id }  %>
                        <%= f.input :price %>
                        <%= f.input :user_id , :as => "hidden",:input_html => { :value => current_user.id } %>
                     </div>

                    <div class="form-actions">
                     <%= f.button :submit %>
                     </div>
                    <% end %>

In script

<script type="text/javascript">
$(".priceaddtokendesc").tokenInput("/stores.json", {
crossDomain: false,
prePopulate: $(".priceaddtokendesc").data("pre"),
theme: "facebook",
allowFreeTagging: true,
resultsLimit: "10",
zindex: 9999,
propertyToSearch: "name",
allowCreation: true,
creationText: 'Add new element',
preventDuplicates: true
});

On create i would like to store Store_id => store_tokens, also i have tried adding through controller but it won'work.

def create
  @storedescription = Storedescription.new(storedescription_params)

  @storedescription.store_id = @storedescription.store_tokens  

  @storedescription.save 
  respond_with(@storedescription)

end

But every time i get null result.

What is the best way to implement this process?

0

There are 0 answers