I am using the rails3-jquery-autocomplete gem and it works neat when using it for fields that exist in the model. However, I have been trying to use it for associations and I fail to see how to make it work. So let’s explain what I have:
Models:
class Receipt < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :receipts
end
Controller
class Admin::ReceiptsController < AdminController
autocomplete :user, :name
def index
@receipts = Receipt.all
end
def show
@receipt = Receipt.find_by_id(params[:id])
end
def edit
@receipt = Receipt.find_by_id(params[:id])
@users = User.all
end
end
View (form):
<%= form_for(@receipt, :url => admin_receipt_path, :html => { :multipart => true }) do |f| %>
<div class="clearfix">
<%= f.label :value, "Value($)" %>
<div class="input"><%= f.text_field :value %></div>
</div>
<div class="clearfix">
<%= f.label :user_id, "User" %>
<div class="input">
<%= f.autocomplete_field :user_id, autocomplete_user_name_admin_receipts_path %>
</div>
</div>
.....
The thing is… I am able to fetch user names, but I want to actually store the user id in there. The same way I would like to show the name when the admin tries to edit an existing receipt with a user associated. Something that I am able to do with this drop down:
<div class="clearfix">
<%= f.label :user_id, "User" %>
<div class="input"><%= f.select :user_id, @users.collect {|p| [ p.name, p.id ] },{:prompt => 'Select a User'} %></div>
</div>
I am failing to see how would I do this with this gem….
Ryan Bates did a screencast on this. Clean and well explained
Screencast
If you don’t feel like subscribing try torrent