1

我正在使用rails3-jquery-autocomplete gem,并且在将它用于模型中存在的字段时它工作得很好。但是,我一直在尝试将它用于关联,但我不知道如何使它工作。所以让我们解释一下我所拥有的:

型号

class Receipt < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :receipts
end

控制器

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

查看(表格)

<%= 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>
.....

问题是......我能够获取用户名,但我想实际将用户 ID 存储在那里。当管理员尝试编辑与关联用户的现有收据时,我想以同样的方式显示名称。我可以用这个下拉菜单做的事情:

<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>

我看不到如何用这颗宝石做到这一点....

4

1 回答 1

2

Ryan Bates 对此进行了截屏。干净且解释清楚

截屏

如果您不想订阅,请尝试 torrent

于 2012-10-03T21:22:46.557 回答