gpt4 book ai didi

ruby-on-rails - 你如何从另一个模型自动完成?

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:14 25 4
gpt4 key购买 nike

我在 Auto-complete Associations 关注了 Railscast但我被困在自动完成的一半。我没有使用 Prototype,而是使用 Jquery,我不知道如何让自动完成功能发挥一半的作用。它是怎么做到的?

这是与 Railscast 相比的定制:

产品型号:

def location_name
location.business_name if location
end

def location_name=(business_name)
self.location = Location.find_by_business_name(business_name) unless business_name.blank?
end

上面创建了一个虚拟属性,我在其中定义了我的位置模型 :business_name进入location_name对于 <%= f.text_field :location_name %>我的产品形式,因为产品属于位置。

编辑:这是使用 Jquery Autocomplete Gem但我对其他选择持开放态度。

我的产品 :name很有魅力;

<%= f.autocomplete_field :name, autocomplete_product_name_products_path %>

但是如果我为 :location_name 放这样的东西这不好;

<%= f.autocomplete_field :location_name, autocomplete_product_location_name_products_path %>

最佳答案

很简单,只需要添加attr_accessor,这是我从另一个项目中完成的代码:

<%= form_for(@business_address) do |f| %>
<%= f.error_messages %>
<%= f.label :name, "Address" %><br />
<%= f.autocomplete_field :name, autocomplete_business_address_name_business_addresses_path %>
<%= f.label :business_name, "Business" %>
<%= f.autocomplete_field :business_name, autocomplete_business_name_business_addresses_path %>
<%= f.submit %>
<% end %


class BusinessAddress < ActiveRecord::Base
attr_accessible :name, :business_name
belongs_to :business
attr_accessor :business_name


def business_name
business.name if business
end

def business_name=(name)
self.business = Business.find_or_create_by_name(name) unless name.blank?
end
end

class BusinessAddressesController
autocomplete :business, :name, :full => true
autocomplete :business_address, :name, :full => true
end

路线.rb

resources :business_addresses do
get :autocomplete_business_name, :on => :collection
get :autocomplete_business_address_name, :on => :collection
end

确保您在应用程序布局中指定了所需的文件,否则由于某些奇怪的原因它无法工作(rails 3.0.9)

<%= javascript_include_tag "autocomplete-rails", "jquery-ui-1.8.16.custom.min" %>

关于ruby-on-rails - 你如何从另一个模型自动完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6554840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com