首页 > 解决方案 > 允许用户在 Rails 中只提交一次表单

问题描述

我正在开发一个用户可以提交不同调查的应用程序。每个调查都有多个问题。我有一个场景,我想限制用户只提交一次调查,这意味着如果用户提交调查并且他再次提交相同的调查,他不应该被允许再次提交该调查并且应该显示错误消息'您已经提交了该调查'。

用户模型

class User < ApplicationRecord
 # Include default devise modules. Others available are:
 # :confirmable, :lockable, :timeoutable and :omniauthable
 devise :database_authenticatable,
     :recoverable, :rememberable, :trackable, :validatable
 belongs_to :role
 has_many :survey_answers
 def full_name
  full_name = "#{self.first_name} #{self.last_name}".strip
  full_name.present? ? full_name : self.user_name
 end
end

调查模型

class Survey < ApplicationRecord
  has_attached_file :logo
  do_not_validate_attachment_file_type :logo

  has_many :questions, -> { order(position: :asc) } , :dependent => 
  :destroy
  accepts_nested_attributes_for :questions, allow_destroy: true
  has_many :survey_answers
end

问题模型

class Question < ApplicationRecord
  belongs_to :survey, optional: true
  acts_as_list scope: :survey
  has_many :question_options, :dependent => :destroy
  accepts_nested_attributes_for :question_options, allow_destroy: 
  true, reject_if: proc { |attributes| attributes['title'].blank? }
  has_many :survey_answers
end

调查答案模型

class SurveyAnswer < ApplicationRecord
  belongs_to :question, optional: true
  belongs_to :user, optional: true
  belongs_to :survey, optional: true
end

标签: ruby-on-rails

解决方案


推荐阅读