我有三个相关的表格:
当我创建一个新的事实时,我需要在事实中加入新的形式,指示一个值来创建一个限制,并选择一个特性。我想知道使用复杂表单http://railscasts.com/episodes/73-complex-forms-part-1是否可以应用到我的问题上?
发布于 2014-04-17 00:26:00
在MrYoshiji @MrYoshiji的建议之后,我能够用这种方法解决我的问题:
#事实模型
class Fact < ActiveRecord::Base
attr_accessible :description, :restriction
belongs_to :restriction, :dependent => :destroy
accepts_nested_attributes_for :restriction
end#约束模型
class Restriction < ActiveRecord::Base
attr_accessible :threshold, :feature
has_many :facts
belongs_to :feature
accepts_nested_attributes_for :feature
end#控制器
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
...#事实视图
<%= form_for(@fact) do |f| %>
...
<%= fields_for "fact",@fact.restriction do |restr_form| %>
...
<%= fields_for "fact",@fact.restriction.feature do |feat_form| %>
...任何疑问法官都会问。
发布于 2014-04-15 15:30:22
我认为你可以这样做:
# 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您应该得到这样的参数:
{
'fact' => {
'some_stuff' => 'some_values',
'restriction_attributes' => {
'some_other_stuff' => 'some_other_values',
'feature_attributes' => {
'stuff' => 'values'
}
}
}
}https://stackoverflow.com/questions/23087947
复制相似问题