问题&答案 - 不接受用户输入

时间:2017-01-16 10:21:22

标签: ruby-on-rails ruby-on-rails-4

我正在建立一个用户输入问题的问答网站,我接受用户输入并将其与数据库进行比较,如果答案是正确的,我会将问题的值添加到记分板,但是我遇到的问题是用户输入没有通过模型传递,当我设置@user_input = params[:content]时,它总是返回null,我相信这是因为我使用了命名空间/嵌套模型。

行动计划:

Get the current answer from the database for the current_question_id, and set as a varaiable

Check Users input against the answer in the database
    if question_id & user_submitted_answer exists in database
        create record in submission's table with status == correct
    else
        create record in submissions table with status  == Incorrect

型号:

成员/问题

class Members::Question < ActiveRecord::Base
  belongs_to :category
  belongs_to :point
  belongs_to :event

  has_many :submissions
  has_one :answer
end

提交

class Submission < ActiveRecord::Base
    belongs_to :question
    belongs_to :member
end

路线:

Rails.application.routes.draw do

  #Root Routes
  root 'home#index'  
  get 'home/index'
  get 'home/about'  

  mount RailsAdmin::Engine => '/eriadmin', as: 'rails_admin'

  #Devise Controller
  devise_for :members

  #Members namepsace
  get '/members/', to: 'members/dashboard#index', as: 'members_dashboard',  only: [:show]

  resources :answers

  namespace :members do
    resources :questions,  only: [:index,:show] do
      resources :submissions 
    end
  end
end

提交控制器 创建方法

@answer_check = Answer.where("question_id = ? AND content = ?",set_members_question,  set_user_submission)
    if @answer_check.present?

        flash.alert = 'Answer There'
        @submission = @members_question.submissions.create(params[:submission].permit(:question_id))
        @submission.member_id =  current_member.id

        @submission.content = Submission.find_by(params[:content])


    else
        flash.alert = 'NOPE NOT There'
        @submission = @members_question.submissions.create(params[:submission].permit(:question_id))
        @submission.content = "Incorrect"
        @submission.member_id =  current_member.id
    end

def set_user_submission
  @members_question =  Submission.find(params[:content])
end 

user_submitted_answer:内容未通过&#34; Questions / Show&#34;中的表单传递。进入提交控制器?

我这样做是错误的,接近它是错误的还是我可以使用的rails方法更有效并且可以实现我的需要?

我当前的代码,Always返回false,而users_input没有插入数据库。

1 个答案:

答案 0 :(得分:0)

从我看到的,您在任一情况下创建提交,然后分配内容和成员ID而不保存它。

请记住,create方法初始化对象并保存它,之后需要再次保存您指定的任何值。所以我已经调整了你的代码,如下所示,提交对象被初始化,然后你添加内容和member_id,并保存它。

if @answer_check.present?
    flash.alert = 'Answer There'
    @submission = @members_question.submissions.new(params[:submission].permit(:question_id))
    @submission.member_id =  current_member.id

    @submission.content = Submission.find_by(params[:content])
    @submission.save
else
    flash.alert = 'NOPE NOT There'
    @submission = @members_question.submissions.new(params[:submission].permit(:question_id))
    @submission.content = "Incorrect"
    @submission.member_id =  current_member.id
    @submission.save
end

希望这有效,如果认为是正确的,请取消投票!

干杯!