Создание опросов с помощью accepts_nested_form_for - PullRequest
1 голос
/ 28 октября 2010

Я работал с rails3 и пытался создать простое приложение для съемки, но возникли некоторые проблемы.Я могу создавать вопросы просто отлично, но когда дело доходит до создания опроса, который могут пройти люди, я сталкиваюсь с некоторыми проблемами.Для одного ответы не присваиваются: user_id или: survey_id.Ниже приводится копия моих контроллеров, моделей и представлений.

Survey Controller

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

Survey Model

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

1 Ответ

0 голосов
/ 28 октября 2010

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

s.hidden_field :user_id, :value => x

Вот как я сделал скрытые поля, вы просто помещаете туда переменные.Я столкнулся с проблемами слияния, не передавая его как пару ключ-значение.


Что вы используете?Черт возьми, я не очень понимаю, как это работает.

Это все, что тебе нужно, чтобы все работало.

Модель опроса

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 %>
...