我有两个要在创建操作之前使用的视图。
第一个视图是 add_sample_details.html.erb
<% form_tag add_expt_details_samples_path :method => :post do %>
<% for sample in @samples %>
<% fields_for "samples[]", sample do |form| %>
<fieldset>
<legend>Sample Name: <%= sample.name %></legend>
<p><center><%= form.label :sample_title %>
<%= form.text_field :sample_title, :size => 25 %></center></p>
<table>
<tr>
<td>
<%= form.label :taxon_id %>
<%= form.text_field :taxon_id, :size => 15 %>
</td>
<td>
<%= form.label :scientific_name %>
<%= form.text_field :scientific_name, :size => 20 %>
</td>
<td>
<%= form.label :common_name %>
<%= form.text_field :common_name, :size => 15 %>
</td>
</tr>
</table>
<p>
<center>
<%= form.label :sample_descripition %><br \>
<%= form.text_area :description %>
</center>
</p>
</fieldset>
<% end %>
<% end %>
<p><center><%= submit_tag "Next" %></center></p>
<% for samp in @samples %>
<%= hidden_field_tag("sample_ids[]", samp.id) %>
<% end %>
<% end %>
在 SamplesController 中,add_expt_details 看起来像这样
def add_expt_details
# Collect the samples that were sent
@expt_samples = Sample.find(params[:sample_ids])
end
add_expt_details.html.erb 看起来像这样
<% form_for @expt_samples, :url => create_study_samples_path, :html => { :method => :put } do |f| %>
<% @expt_samples.each do |samp|%>
<% f.fields_for :expts do |form| %>
<%= form.label :experiment_title %>
<%= form.text_field :expt_title, :size => 15 %><br \>
<% end %>
<% end %>
<p><center><%= submit_tag "Next" %></center></p>
<% end %>
我的 create_study 动作是这样的
def create_study
@study = Study.new(params[:study])
# this method collects all the samples from the add_sra_details view from the hidden_field_tag
if current_user.id?
# Put the current user_id in the study.user_id
@study.user_id = current_user.id
if @study.save # Save the values for the study
# Update the Sample attributes
@samples = Sample.update(params[:samples].keys, params[:samples].values).reject { |p| p.errors.empty? }
# For all those sample_ids selected by the user, put the study ids in the sample_study_id
@samples.each do |samp|
@study.samples << samp
end
# get the ids_sent from the add_expt_details
@expt_samples = Sample.find(params[:id])
# A Flash message stating the details would be prefereable..! (Means you have to do it)
flash[:success] = "Your Study has been Created"
redirect_to add_expt_details_samples_path
else
flash[:error] = "Study Faulty"
render :action => "add_sra_details"
end
end
end
当我保留@expt_samples = Sample.find(params[:id]) 时收到的错误消息是“nil:NilClass 的未定义方法‘键’”
如果我没有@expt_samples,它会给我一个错误“Couldn't Find id in Sample”
有人可以建议我如何从一个表单更新一组样本 ID,并创建新的 Expt 模型记录,这些记录与另一种表单的 sample_ids 相关联。
所有建议表示赞赏。
干杯