【问题标题】:Best way to handle multiple associated models in a form?在一个表单中处理多个关联模型的最佳方法?
【发布时间】:2013-01-08 04:36:33
【问题描述】:

我有一个相当简单的设置:

models/person.rb

has_many :links

models/link_category.rb

attr_accessible :title
has_many :links

models/links.rb

attr_accessible :person_id, :link_category_id, :url
belongs_to :person
belongs_to :link_category

链接类别的示例可能是“facebook、twitter、pinterest、wordpress、博客等”。

我想要创建的,尽可能 DRY 和 RESTful,是一个单独的页面,其中列出了所有链接类别和一个文本字段,供他们输入(或更新,如果已经提供)每个类别的 url。

例如,http://example.com/person/23/links/edit 之类的内容可能会显示如下形式:

Facebook:_____________ em>_______

推特:__ http://twitter.com/example __

Wordpress:_____________ em>______

Pinterest:_____________ em>______

我想知道是否有人有一种优雅的方式来做到这一点,因为它在许多网站中变得非常普遍。

【问题讨论】:

    标签: ruby-on-rails-3 forms models model-associations


    【解决方案1】:

    我认为您的要求与我曾经要求的非常相似:

    Rails: How do I prepend or insert an association with build?

    您可以在控制器中调用类似的函数,也可以调用 :after_initialize

    要利用它,您需要将 has_many :link_categories, through: :links 添加到您的 Person 模型中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 2021-12-31
      • 2014-11-29
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      相关资源
      最近更新 更多