我很努力想出正确的方法来设计一个表格,这将允许我输入两个不同模型的数据。形式是为一个“事件”,它具有以下关系:如何在一个表单中为多个模型使用嵌套表单?
belongs_to :customer
belongs_to :user
has_one :incident_status
has_many :incident_notes
accepts_nested_attributes_for :incident_notes, :allow_destroy => false
因此事件被分配到“客户”和“用户”,用户能够添加的“注意”到事件。我在表单的注释部分遇到问题。这里是如何的形式提交:
{"commit"=>"Create",
"authenticity_token"=>"ECH5Ziv7JAuzs53kt5m/njT9w39UJhfJEs2x0Ms2NA0=",
"customer_id"=>"4",
"incident"=>{"title"=>"Something bad",
"incident_status_id"=>"2",
"user_id"=>"2",
"other_id"=>"AAA01-042310-001",
"incident_note"=>{"note"=>"This is a note"}}}
这似乎是试图将incident_note添加为场下的“事件”,而不是一个incident_id外键链接回创建的incident_note表的新条目事件。
这里是 'IncidentNote' 模式:
belongs_to :incident
belongs_to :user
这里是 '事故' 的形式:
<% form_for([@customer,@incident]) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :other_id, "ID" %><br />
<%= f.text_field :capc_id %>
</p>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= label_tag 'user', 'Assign to user?' %>
<%= f.select :user_id, @users.collect {|u| [u.name, u.id]} %>
</p>
<p>
<%= f.label :incident_status, 'Status?' %>
<%= f.select :incident_status_id, @statuses.collect {|s| [s.name, s.id]} %>
</p>
<p>
<% f.fields_for :incident_note do |inote_form| %>
<%= inote_form.label :note, 'Add a Note' %>
<%= inote_form.text_area :note, :cols => 40, :rows => 20 %>
<% end %>
</p>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
最后,这里有新的incident_controller条目和创建。
新:
def new
@customer = current_user.customer
@incident = Incident.new
@users = @customer.users
@statuses = IncidentStatus.find(:all)
@incident_note = IncidentNote.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @incident }
end
end
创建:
def create
@users = @customer.users
@statuses = IncidentStatus.find(:all)
@incident = Incident.new(params[:incident])
@incident.customer = @customer
@incident_note = @incident.incident_note.build(params[:incident_note])
@incident_note.user = current_user
respond_to do |format|
if @incident.save
flash[:notice] = 'Incident was successfully created.'
format.html { redirect_to(@incident) }
format.xml { render :xml => @incident, :status => :created, :location => @incident }
else
format.html { render :action => "new" }
format.xml { render :xml => @incident.errors, :status => :unprocessable_entity }
end
end
end
我真的不知道在哪里看在这一点上。我相信这只是我当前Rails技能的限制(我不太了解)。所以如果有人能指出我的方向是正确的,我会非常感激。请让我知道是否需要更多信息!
谢谢!
感谢您的答复。我认为这是问题。现在我收到了其他错误,因为我修补了一些,所以我还没有确认。 :) – Magicked 2010-05-06 16:59:45