0

Having a small problem saving client_ids. I don't understand where i'm going wrong. Basically i have 3 models

Client, Message and Delegateship. I would like to send a message to multiple clients at the same time. I am trying to use 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

My Message model

class Message < ActiveRecord::Base
  has_many :delegateships
  has_many :clients, through: :delegateships

end

Delegateship Model

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

Message controller

class MessagesController < ApplicationController

  private

    def message_params
      params.require(:message).permit(:event_id, :content, :user_id, client_ids: [:id]
                    )
    end
end

ClientsController

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

Terminal

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

The clients display without any issues but i can't get them to save on the delegateship table. I've looked at the following to try for the solution to my problem:

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/

Benjamin
  • 2,108
  • 2
  • 26
  • 46

2 Answers2

4

I would try removing :id from your strong_params because that might be the source of the problem and it ignores the actual array since client_ids is not an array of hashes. Your syntax here might be causing it to ignore the data being sent in.


Take a look at this example that I made here: https://github.com/excid3/habtm_example

Clone this, bundle, rake db:migrate, and rails s to get it up and running. It has /clients and /messages routes. Create a few clients and then test with creating messages to those clients.

Specifically the /messages/new form.

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

This sets up a select box to choose from all available clients when sending a message. It passes in the client_ids array to the message which Rails knows to set this up with the relationship.

You also need to tell the MessageController to accept an array of client_ids with strong_params:

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

It's also using select2 to style the select box.

excid3
  • 1,658
  • 15
  • 31
0
    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
himeshp
  • 353
  • 4
  • 12