【问题标题】:Rails 4 HABTM Select2Rails 4 HABTM 选择2
【发布时间】: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


    【解决方案1】:

    我会尝试从您的 strong_params 中删除 :id,因为这可能是问题的根源,并且它忽略了实际数组,因为 client_ids 不是哈希数组。您在此处的语法可能会导致它忽略正在发送的数据。


    看看我在这里制作的这个例子:https://github.com/excid3/habtm_example

    克隆这个、bundle、rake db:migrate 和 rails s 以使其启动并运行。它有 /clients 和 /messages 路由。创建一些客户端,然后通过向这些客户端创建消息进行测试。

    特别是 /messages/new 表单。

    <%= hidden_field_tag "message[client_ids][]", nil %>
    <%= f.select :client_ids, Client.all.map{ |c| [c.name, c.id]}, {}, multiple: true %>
    

    这会设置一个选择框,以便在发送消息时从所有可用客户端中进行选择。它将client_ids 数组传递给Rails 知道的消息来设置关系。

    您还需要告诉 MessageController 接受带有 strong_params 的 client_id 数组:

    def message_params
      params.require(:message).permit(:body, client_ids: [])
    end
    

    它还使用 select2 来设置选择框的样式。

    【讨论】:

    • 谢谢你,克里斯,它就像一个魅力。再次感谢您的帮助。 client_ids:[]
    【解决方案2】:
        select2 style wont apply. i just want a simple drondown
    
        _form.html.erb
         <div class="col-sm-8" name="account">
              <%= hidden_field_tag "message[branch_id][]", nil%>      
              <%= f.select :branch_id, Branch.all.map{ |c| [c.branch_name, c.id]}, {} %>
            </div>
          </div>
    
    
     $("#message_branch_id").select2({
      placeholder: "Select a Branch",
      allowClear: true
    });
    
     def course_params
          params.require(:course).permit(:name, :start_date, :end_date, :branch_id)
        end
    
    class Branch < ActiveRecord::Base
      has_many :courses
    end
    
    class Course < ActiveRecord::Base
      belongs_to :branch
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 2015-08-23
      • 1970-01-01
      相关资源
      最近更新 更多