首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 3-3个表之间关联的复杂表单

Rails 3-3个表之间关联的复杂表单
EN

Stack Overflow用户
提问于 2014-04-15 15:19:39
回答 2查看 89关注 0票数 1

我有三个相关的表格:

  • 具有1限制的 (* - 1)
  • 以及具有1特性的 (* - 1)

当我创建一个新的事实时,我需要在事实中加入新的形式,指示一个值来创建一个限制,并选择一个特性。我想知道使用复杂表单http://railscasts.com/episodes/73-complex-forms-part-1是否可以应用到我的问题上?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-17 00:26:00

在MrYoshiji @MrYoshiji的建议之后,我能够用这种方法解决我的问题:

#事实模型

代码语言:javascript
复制
 class Fact < ActiveRecord::Base
 attr_accessible :description, :restriction
 belongs_to :restriction, :dependent => :destroy

 accepts_nested_attributes_for :restriction

 end

#约束模型

代码语言:javascript
复制
class Restriction < ActiveRecord::Base
attr_accessible :threshold, :feature
has_many :facts
belongs_to :feature

accepts_nested_attributes_for :feature  
end

#控制器

代码语言:javascript
复制
def new
    @fact = Fact.new
    @restriction = @fact.build_restriction
    @feature = @restriction.build_feature
    ...

def create
    @fact = Fact.new(fact_params)
    @feature = Feature.find(params[:feature][:id])
    @restriction = Restriction.new(:threshold => params[:fact][:threshold])
    @restriction.feature = @feature
    @restriction.save

    @fact.restriction = @restriction
    @fact.save
    ...

#事实视图

代码语言:javascript
复制
 <%= form_for(@fact) do |f| %>
 ...
     <%= fields_for "fact",@fact.restriction do |restr_form| %>
     ...
         <%= fields_for "fact",@fact.restriction.feature do |feat_form| %>
         ...

任何疑问法官都会问。

票数 0
EN

Stack Overflow用户

发布于 2014-04-15 15:30:22

我认为你可以这样做:

代码语言:javascript
复制
# Fact model
accepts_nested_attributes_for :restriction
# Restriction model
accepts_nested_attributes_for :feature

# controller
@fact = Fact.new
@restriction = @fact.restriction.new
@feature = @restriction.feature.new

# view
form_for @fact do |fact_fields|
  # ...
  fields_for @restriction do |restriction_fields|
    # ...
    fields_for @feature do |feature_fields|
      # ...
    end
  end
end

您应该得到这样的参数:

代码语言:javascript
复制
{ 
  'fact' => {
     'some_stuff' => 'some_values',

     'restriction_attributes' => {
       'some_other_stuff' => 'some_other_values',

       'feature_attributes' => {
         'stuff' => 'values'
       }
     }
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23087947

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档