Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails3-jquery-autocomplete reference id with formtastic

I just started my Rails app and I have the following problem - I want to use the jQuery UI and autocomplete, and therefore have used the gem rails3-jquery-autocomplete. I also use formtastic for my rails forms.

I have two models:

Customer:

class Customer < ActiveRecord::Base
  has_many :carts
end

create_table :customer do |t|
  t.column :lastname, :string
  t.column :forename, :string
end

Cart:

class Cart < ActiveRecord::Base
  belongs_to :customer
end

create_table :cart do |t|
  t.column :costumer_id, :integer
end

As explained in the doc of the gem I made the autocomplete config in my CartController:autocomplete :customer, :lastname, :full => true

In my view with the formtastic code it looks like this:

<%= semantic_form_for @cart do |f| %>
    <%= f.inputs do %>
    <%= f.input :customer,
        :as => :autocomplete,
        :url => autocomplete_customer_lastname_carts_path,
        :id_element => '#cart_customer_id' %>

The main question that I have is, how to deal with the id stuff. I mean, I want to store the reference id of the customer in my cart model and not the name itself. I recognized the possibility to take the :id_element option to reference an id input field for storing the id in the form. I figured out, that there seems to be a problem with the formtastic combination, and found a potential solution.

I could do this, with an <%= f.input :customer_id, :as => :hidden %>, but I really don't know what to write in the line: <%= f.input :customer, :as => :autocom.... Is :customer the right solution for this? This approach would give me the following: "cart"=>{"customer"=>"26","customer_id"=>"0"}

Does anyone have an idea, possibly I totally misunderstand the whole :id_element thing...

like image 913
Mario David Avatar asked Mar 18 '12 14:03

Mario David


1 Answers

You also got a wrong column name into your migration.

create_table :cart do |t|
  t.column :customer_id, :integer
end

ok i found it :)

so you need to make an hidden_field with customer_id and tell to autocomplete to update this input value. the tag :update_elements => {}

<%= autocomplete_field_tag "cart_customer_name", "" , autocomplete_customer_lastname_carts_path, :id_element => "#customer_customer_id", :update_elements => {} %><br />
<%= f.hidden_field :customer_id %>

So :id_element is the id element you want to update when a result is selected.

like image 97
rbinsztock Avatar answered Oct 17 '22 12:10

rbinsztock