Создание опросов с accepts_nested_form_for

Я работал с 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

Маршруты.рб

    resources :surveys do
        get 'take', :on => :member
        put 'submit', :on => :member
    end

person salbito    schedule 28.10.2010    source источник


Ответы (1)


попробуйте добавить еще одно скрытое поле с идентификатором пользователя в частичном ответе.

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 %>
person thenengah    schedule 28.10.2010
comment
Спасибо. это сработало ... но как мне сделать так, чтобы они только сейчас обновляли их ответы. потому что, если я заполню форму и обновлю ее после создания ответов... она вернет формы, заполненные старыми ответами и новыми ответами - person salbito; 28.10.2010
comment
Я не уверен, почему отображаются старые и новые ответы. Вы имеете в виду, что дубликаты создаются? Я просто не слишком уверен. - person thenengah; 28.10.2010