Jquery令牌使用has_many关联和连接表输入。

时间:2017-11-11 20:39:53

标签: javascript jquery ruby-on-rails jquery-tokeninput

我有3个模特

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

描述模型

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

和商店描述模型

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

我有一个商品描述表单

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

在剧本中

<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
});

在创建时,我想存储Store_id =&gt; store_tokens,我也试过通过控制器添加,但它赢得了工作。

def create
  @storedescription = Storedescription.new(storedescription_params)

  @storedescription.store_id = @storedescription.store_tokens  

  @storedescription.save 
  respond_with(@storedescription)

但每次我得到null结果。

实施此流程的最佳方式是什么?

0 个答案:

没有答案