在rails中自动完成nested_form字段

时间:2013-11-06 17:15:49

标签: ruby-on-rails ruby autocomplete nested-forms

我最近开始学习rails 3。我正在考虑实现自动完成功能的最佳方法。

我的rails应用程序中有4个模型,具有以下结构。

class User
  has_many :friendships
  has_many :bills
end

class Friendship
  belongs_to :user
end

class Bill
  belongs_to :user
  has_many :bill_splits
end

class BillSplit
  belongs_to :bill
  has_on :friendship
end

BillBillSplit模式背后的想法是,一旦用户创建帐单,帐单将根据与帐单共享的朋友数量自动拆分。

我在bill_split上使用嵌套属性,这样我就可以使用单个表单来创建bill和bill_split条目。我想为friend_name(用户的Friendship朋友列表)和friendship_id添加自动填充字段,然后保存。我想知道最好的方法是什么。

执行此操作的一种可能方法是在friend_name中创建一个虚拟属性bill_split,该属性会自动填充名称并填充friendship_id。另一种方法是删除friendship_id并将其替换为friend_name。有没有其他方法可以实现这一目标?

另外,是否也可以引用另一个模型中的字段而不仅仅是模型本身?

谢谢!

3 个答案:

答案 0 :(得分:2)

I understand that you want to implement autocompleting text fields with nested forms. First off, I do not see any nested associations in your models. If the main form is for a bill, then you should add the following to its model:

accepts_nested_attributes_for :bill_splits

While bill_splits could stand alone, adding the above line to the Bill model will help in the controller, where you implement :bill_split_attributes array of params. Then, in your form, you call a fields_for :bill_splits, and proceed with nested forms as normal.

Now, in regards to autocompletion... Whether you are still on Rails 3 or have upgraded to Rails 4, the rails-jquery-autocomplete gem is the official repository supporting both! It includes great documentation, as well as a sample app with nested form examples. The gem uses jQuery UI autocomplete library, and incorporates ActiveRecord entries into the dataset submitted.

Unfortunately, with the information you have provided, I am unable to help further with configuring the nested forms. As I said before, I do not know your table structure or your current code to better evaluate. Good news, the gem's maintainer is active and answering questions/issues!

答案 1 :(得分:0)

您可能希望看到此截屏视频http://railscasts.com/episodes/102-auto-complete-association

如果您使用rails4,请查看 rails4-autocomplete gem

答案 2 :(得分:-1)

我设法用http://twitter.github.io/typeahead.js/做到了希望这可以帮助你