0

だから私は入れ子になったフォームを持つレールアプリのこの部分に取り組んでいます。検証を機能させるのに問題があります。したがって、親フォームは質問を格納するモデルであり、子フォームは回答を格納するモデルです。

質問には、数字 (テキスト フィールド)、はい/いいえ (ラジオ ボタン)、賛成/反対 (ラジオ ボタン) の 3 種類があります。

回答モデルに簡単な検証があります。validates :value, presence: true

たとえば、タイプ番号の質問を作成すると、テキスト フィールドが生成され、それを空として送信すると、検証が機能し、ページにエラーが表示されます。ただし、両方ともラジオ ボタンである他の 2 つのオプションのいずれかを選択すると、選択せずにフォームを送信でき、検証が機能しません。コンソールで、質問のみがデータベースに挿入されていることに気付きましたが、回答は (ラジオ ボタン フォームでは) 挿入されていません。通常、少なくとも nil 値が渡されると想定しますが、INSERT クエリは表示されません。

ラジオ ボタン フォームに非表示フィールドを作成し、選択したラジオ ボタンが変更されるたびにラジオ ボタンの値を非表示フィールドに設定する変更ハンドラを作成して、少しごまかしました。ただし、javascript が無効になっている場合に備えて、バックアップを取っておくことは常に良いことなので、もっと深く掘り下げて実際の問題を突き止めたいと思います。

回答モデル

class Answer < ActiveRecord::Base
  attr_accessible :value, :user_id, :meter_id, :question_id
  belongs_to :user
  belongs_to :question

  validates :value, presence: true, :numericality => true

  before_save :associate_with_meter_id
  before_save :associate_with_user_id

  def associate_with_meter_id
    self.meter_id = question.user.meter_id
  end

  def associate_with_user_id
    self.user_id = question.user.id
  end

end

質問モデル

class Question < ActiveRecord::Base
    attr_accessible :description, :taxonomy, :user_id, :answers_attributes
  belongs_to :user
  has_many :answers

  accepts_nested_attributes_for :answers

  validates :description, presence: { :on => :create }
  validates :taxonomy, presence: { :on => :create }

  def relevance_score
    rand
  end

end

ログ

Started POST "/questions" for 127.0.0.1 at 2012-06-12 09:21:25 -0400
Processing by QuestionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"knwvfB6q6Q7qoTprc/3R4Et3r13xWzpAB1Iq8FsRndQ=", "question"=>{"description"=>"How are you?", "taxonomy"=>"yesno"}, "submit_button"=>"Ask"}
  User Load (0.6ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 585460615 LIMIT 1
  SQL (0.1ms)  BEGIN
  SQL (4.3ms)  INSERT INTO `questions` (`avganswer`, `coeff`, `created_at`, `description`, `pval`, `quality`, `rank`, `responses`, `rsquare`, `skips`, `taxonomy`, `updated_at`, `user_id`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["avganswer", nil], ["coeff", nil], ["created_at", Tue, 12 Jun 2012 13:21:25 UTC +00:00], ["description", "How are you?"], ["pval", 0.0], ["quality", 0.0], ["rank", nil], ["responses", nil], ["rsquare", 0.0], ["skips", nil], ["taxonomy", "yesno"], ["updated_at", Tue, 12 Jun 2012 13:21:25 UTC +00:00], ["user_id", 585460615]]
   (0.3ms)  COMMIT
  SQL (0.0ms)  BEGIN
   (0.0ms)  COMMIT
Redirected to http://localhost:3000/questions
Completed 302 Found in 14ms (ActiveRecord: 0.0ms)


Started GET "/questions" for 127.0.0.1 at 2012-06-12 09:21:25 -0400
Processing by QuestionsController#index as HTML
  User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 585460615 LIMIT 1
  Question Load (1.3ms)  SELECT `questions`.* FROM `questions` WHERE `questions`.`user_id` = 585460615
  Rendered shared/_error_messages.html.erb (0.0ms)
  Rendered questions/_form.html.erb (23.9ms)
   (0.5ms)  SELECT COUNT(*) FROM `questions` 
  Rendered questions/index.html.erb within layouts/application (48.8ms)
  Question Load (1.6ms)  SELECT `questions`.* FROM `questions` 
   (0.4ms)  SELECT COUNT(*) FROM `questions` WHERE `questions`.`user_id` = 585460615
  Rendered /Users/gregorygrillone/.rvm/gems/ruby-1.9.3-p194/bundler/gems/gauges-58ad28a906b2/app/views/gauges/_gauge.html.erb (0.1ms)
  CACHE (0.0ms)  SELECT `questions`.* FROM `questions` 
  CACHE (0.0ms)  SELECT COUNT(*) FROM `questions` WHERE `questions`.`user_id` = 585460615
Completed 200 OK in 72ms (Views: 62.2ms | ActiveRecord: 4.2ms)


Started GET "/assets/application.css" for 127.0.0.1 at 2012-06-12 09:21:25 -0400
Served asset /application.css - 304 Not Modified (0ms)
[2012-06-12 09:21:25] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true


Started GET "/assets/application.js" for 127.0.0.1 at 2012-06-12 09:21:25 -0400
Served asset /application.js - 304 Not Modified (0ms)
[2012-06-12 09:21:25] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

質問コントローラー

class QuestionsController < ApplicationController
  respond_to :html, :json

  def index
    @question = current_user.questions.new
    @questions = current_user.questions.all
  end

  def create
    @question = current_user.questions.new(params[:question])
    if !params[:update_button]
      if @question.valid?
        if params[:next_button] || !@question.save
          @questions = current_user.questions.all
          render 'index'
        elsif !params[:next_button] && params[:submit_button] && @question.save
          flash[:success] = "Your question and answer have been saved."
          respond_with @question, :location => questions_path
        end
      else
        @questions = current_user.questions.all
        render 'index'
      end
    else
      @questions = current_user.questions.all
      render 'index'
    end
  end

  def next
    @question = current_user.unanswered.first
    @answer = Answer.new(:question => @question, :user => current_user)
    respond_to do |format|
      format.js
    end
  end
end
4

1 に答える 1

0

ビューコードがフォーム構造を適切に作成していないと思います。

期待する形式でパラメーターを送信する機能/コントローラー テストを作成することで、コントローラー コードが正しいことを確認できるはずです。(アプリの半分を StackOverflow に投稿しようとするよりも、はるかに優れた/高速なフィードバック!)

まともなテストを 1 時間もかからずに作成できるようになり、その知識によって、他のすべての作業がはるかに効率的かつ迅速になります。信じてください。コードを適切にテストする方法を学ぶことには、努力する価値があります。

コントローラーが適切に動作していることを証明すると、ビュー コードがネストされた回答のフォーム入力を適切に作成していないことに気付くでしょう。ログ ファイルから、それらを投稿しようとさえしなかったことがわかります。

作成アクションと更新アクションを分離したい場合があります。異なるボタンをチェックするコードは少し混乱し、ページとコントローラーの間の「契約」を理解するのが難しくなります。(たとえば、次の場合、更新ではなく送信...) それは今問題を引き起こしているわけではありませんが、後で噛まれる前に片付けたいと思うかもしれません。

于 2012-06-12T19:00:44.167 に答える