我一直在使用rails3并且一直在尝试创建一个简单的调查应用程序,但是出现了一些问题。我可以很好地创建问题,但是当创建人们可以采取的调查时,我会遇到一些问题。例如,答案没有被分配:user_id或:survey_id。以下是我的控制器,模型和视图的副本。
调查控制器
def take
@survey = Survey.find(params[:id])
@questions = @survey.questions
@answers = @questions.map{|q| q.answers.build}
@answers.each do |a|
a.survey_id = @survey.id
a.user_id = current_user.id
end
respond_to do |format|
format.html #
end
end
def submit
@survey = Survey.find(params[:id])
respond_to do |format|
if @survey.update_attributes(params[:survey])
format.html { redirect_to(@survey, :notice => 'Survey was successfully submitted.')}
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @survey.errors, :status => :unprocessable_entity }
end
end
end
调查模型
class Survey < ActiveRecord::Base
belongs_to :user
has_many :questions, :dependent => :destroy
has_many :answers, :through => :questions, :dependent => :destroy
validates_presence_of :name, :user_id
accepts_nested_attributes_for :questions, :allow_destroy => true
end
问题模型
class Question < ActiveRecord::Base
belongs_to :survey
has_many :answers
validates_presence_of :question_string, :question_type
accepts_nested_attributes_for :answers, :allow_destroy => true
end
答案模型
class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :user
belongs_to :survey
end
观看视图
%h1 Take the survey
- semantic_form_for @survey, :url => { :action => "submit" } do |s|
- if @survey.errors.any?
%p= pluralize(@survey.errors.count, "error") + " prohibited this survey from being saved"
#survey_errors
- @survey.errors.full_messages.each do |err_msg|
%p= err_msg
#survey_details.header
= s.fields_for :questions do |q|
= q.fields_for :answers do |a|
= render 'answer_fields', :s => a
.actions
= s.commit_button
问题部分
#questions_form.fields
= s.input :question_string, :label => "Question: "
= s.input :question_type, :as => :radio, :collection => [1,2,3,4], :label => "Question Type:"
= s.hidden_field :_destroy
= link_to_function "Remove Question", "remove_fields(this)"
回答部分
#answers_form.fields
= s.label :answer_string, "Answer"
= s.text_field :answer_string
= s.hidden_field :question_id
的routes.rb
resources :surveys do
get 'take', :on => :member
put 'submit', :on => :member
end
答案 0 :(得分:0)
尝试在答案部分中添加另一个隐藏字段和用户ID。
s.hidden_field :user_id, :value => x
这就是我做隐藏字段的方法,你只是把变量放在那里。我没有将它作为键值对传递而遇到了合并问题。
你在用什么? HAML,我真的不明白这是怎么回事。
这就是你需要的一切。
调查模型
has_many :answers
accepts_nested_attributes_for :answers, :allow_destroy => true
控制器不需要额外的代码
视图需要fields_for
<% f.fields for :answers do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<% end %>