【问题标题】:Creating a dropdown in using Rails使用 Rails 创建下拉菜单
【发布时间】:2012-05-09 16:02:00
【问题描述】:

所以我目前有两个具有以下关联的模型:

class DnsRecord < ActiveRecord::Base
  validates :name, :presence => true, :uniqueness => true

  has_one :ip_address

  attr_accessible :name
end

class IpAddress < ActiveRecord::Base
  validates :ipv4, :presence => true, :uniqueness => true, :length => { :maximum => 45 }
  validates :ipv6, :presence => true, :uniqueness => true, :length => { :maximum => 45 }

  belongs_to :dns_record

  attr_accessible :ipv4, :ipv6
end

在 dns_record 视图 (/app/views/dns_records) 中,当我在创建新的 dns_recrod 页面时,我想要一个下拉选择当前存在的 ip_addresses。这样,当我创建一个新的 dns_record 时,它就会有一个关联的 ip_address_id。

我对 ruby​​ 和 rails 很陌生,所以如果有人能指出我正确的方向,将不胜感激。

【问题讨论】:

  • 你确定你的联想吗? DnSRecord belongs_to :ip_address AND IpAddress has_one :dns_record 可以接受吗?如果是这样,您可以使用 collection_select 帮助器轻松处理。
  • 你的问题解决了吗?

标签: ruby-on-rails ruby-on-rails-3 forms drop-down-menu


【解决方案1】:

Twitter 引导程序适合您。 http://twitter.github.com/bootstrap/javascript.html#dropdowns

它将帮助您入门并向您展示如何将下拉菜单合并到您的 Rails 应用程序中。它为您完成所有繁重的工作。享受吧。

【讨论】:

  • 还有其他解决方案,您可以使用 JQuery 自己创建它,但如果您不喜欢 Bootstrap,可以使用基础或 html5 样板项目等替代方案
  • 我说的是
【解决方案2】:

我不确定您的关联是否完全符合您的要求。根据您的问题,我假设您想要:

class DnsRecord < ActiveRecord::Base
  validates :name, :presence => true, :uniqueness => true
  belongs_to :ip_address
end

class IpAddress < ActiveRecord::Base
  validates :ipv4, :presence => true, :uniqueness => true, :length => { :maximum => 45 }
  validates :ipv6, :presence => true, :uniqueness => true, :length => { :maximum => 45 }
  has_one :dns_record
  attr_accessible :ipv4, :ipv6
end

如果是这样,那么您可以使用 collection_select 为 dns_record 对象设置您的 ip_address。示例:

<% form_for @dns_record do |f| %>
  <%= f.collection_select :ip_address_id, IpAddress.all, :id, :ipv4 %>
<% end %>

以上假设您正在使用 @dns_record 对象,并且您的 dns_records 表有一个 ip_address_id (FK) 列。这也将使用 ip_addresses.ipv4 中的值作为下拉列表中的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 2014-05-12
    • 1970-01-01
    相关资源
    最近更新 更多