【发布时间】:2015-12-07 01:27:35
【问题描述】:
保存 client_ids 时遇到一个小问题。我不明白我要去哪里错了。基本上我有 3 个模型
客户、消息和委托。我想同时向多个客户发送消息。我正在尝试使用 select2。
class Client < ActiveRecord::Base
scope :finder, lambda { |q| where("last_name ILIKE :q", q: "%#{q}%") }
def as_json(options)
{ id: id, text: name }
end
has_many :delegateships
has_many :messages, through: :delegateships
CLIENT_SALUTATIONS = [
'Mr.',
'Mrs.',
'Miss.',
'Ms.',
'Dr.'
]
def name
(salutation? && first_name? && last_name?) ? [salutation.capitalize, first_name.capitalize, last_name.capitalize ].join(" ") : email
end
end
我的消息模型
class Message < ActiveRecord::Base
has_many :delegateships
has_many :clients, through: :delegateships
end
委托模式
class Delegateship < ActiveRecord::Base
belongs_to :message
belongs_to :client
end
messages.js.coffee
$ ->
$('.select2-autocomplete').each (i, e) ->
select = $(e)
options = {
multiple: true
}
options.ajax =
url: select.data('source')
dataType: 'json'
data: (term, page) ->
q: term
page: page
per: 5
results: (data, page) ->
results: data
options.dropdownCssClass = 'bigdrop'
select.select2 options
form.html.haml
= simple_form_for(@message) do |f|
= f.error_notification
.form-inputs
= hidden_field :client_ids, '', data: { source: clients_path }, class: 'select2-autocomplete form-control', name: "message[client_ids][]"
= f.association :event, input_html: { id: 'e1'}
= f.input :content
.form-actions
= f.button :submit
消息控制器
class MessagesController < ApplicationController
private
def message_params
params.require(:message).permit(:event_id, :content, :user_id, client_ids: [:id]
)
end
end
客户端控制器
class ClientsController < ApplicationController
def index
@clients = Client.all
respond_to do |format|
format.html
format.json { render json: @clients.where('last_name ILIKE ?', "%#{params[:q]}%"), only: [:id, :last_name] }
end
end
end
终端
Started PATCH "/messages/13i84tc" for 127.0.0.1 at 2014-07-04 09:41:48 +0200
Processing by MessagesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"M5K47IOTTcOF1natNL/6Md4HEKzAJHZABHOa6fOumWw=", "message"=>{"client_ids"=>["3,4,2"], "event_id"=>"1", "content"=>"Dear Sir, \r\n\r\nI thought i would reach out to you regarding the event. "}, "commit"=>"Update Message", "id"=>"13i84tc"}
Message Load (0.3ms) SELECT "messages".* FROM "messages" WHERE "messages"."slug" = '13i84tc' ORDER BY "messages"."id" ASC LIMIT 1
(0.1ms) BEGIN
Client Load (0.3ms) SELECT "clients".* FROM "clients" INNER JOIN "delegateships" ON "clients"."id" = "delegateships"."client_id" WHERE "delegateships"."message_id" = $1 [["message_id", 11]]
(0.3ms) COMMIT
Redirected to http://localhost:3000/messages/13i84
客户端显示没有任何问题,但我无法让它们保存在委托表上。我查看了以下内容以尝试解决我的问题:
http://gistflow.com/posts/428-autocomplete-with-rails-and-select2 http://luksurious.me/?p=46 http://railscasts.com/episodes/17-habtm-checkboxes-revised http://railscasts.com/episodes/258-token-fields-revised http://ivaynberg.github.io/select2/
【问题讨论】:
标签: ruby-on-rails ruby jquery-select2 has-and-belongs-to-many