Ruby on rails 如何将自定义投票按钮添加到rails应用程序
所以这里有一个想法Ruby on rails 如何将自定义投票按钮添加到rails应用程序,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,所以这里有一个想法 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 类问题
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
类问题
对第一个问题的答复: 在QuestionsController创建方法中,您只需输入一些代码,如:
if user.questions.length > 3
#tell them they can't ask more questions
else
#create the question
end
第二点:
而且,我认为把投票权作为自己的资源是没有意义的。我只是将“投票”或“投票”定义为答案上的一个字段。当一个答案被投赞成票时,您只需增加answer.voces。尽管取决于您的用例,但如果您想更深入地定制验证,您可以委托验证,假设
用户id
是嵌套在问题
模型中的用户
列
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
类问题:user\u id
....
结束
类LengthValidator
你的投票类,它应该有所属的:答案而不是:问题(或者你的有一个在错误的类中)我更喜欢将投票作为它自己的资源,并且有一个与之相关联的用户id,这样用户就可以看到他们投了什么票,甚至可以更改他们的投票。哦,是的,那就有道理了