0

だからここにアイデアがあります

class Question < ActiveRecord::Base
  has_many : answers
end

class Answer < ActiveRecord::Base
  belongs_to :question
  has_one :vote
end

class Vote < ActiveRecord::Base
  belongs_to :question
end
  1. ユーザーが質問できる質問の数を制限するにはどうすればよいですか?
  2. これのより良い方法はありますか?
4

2 に答える 2

1

最初の質問への回答:

QuestionsController の create メソッド内に、次のようなコードを記述します。

if user.questions.length > 3
  #tell them they can't ask more questions
else
  #create the question
end

2番目に:

また、投票を独自のリソースにすることは意味がないと思います。「投票」または「投票」を Answer のフィールドとして定義するだけです。回答が投票されたら、Answer.votes を増やすだけです。ユースケースにもよるけど

于 2013-11-02T14:25:30.333 に答える
0

さらに、検証をより詳細にカスタマイズしたい場合は、モデルにネストされた列でuser_idあると仮定して、検証を委任することができますuserquestion

class Question < ActiveRecord::Base
  validates_with LengthValidator, :field => :user_id
....
end

class LengthValidator < ActiveModel::Validator
  def validate(record)
    if options[:fields].any?
     #put the above conditional of @Accipheran
  end
end
于 2013-11-02T15:54:24.343 に答える