简体   繁体   English

Ruby on Rails使用模型协会

[英]Ruby on Rails Use Model Association

I have the rails_best_practices gem and I'm getting the following warning: 我有rails_best_practices宝石,并且收到以下警告:

APP/app/controllers/users_controller.rb - use model association (for @user_answer)

in reference to this gist of code: 参照以下代码要点:

begin
  @user_answer = @user.user_answers.where(:question_id => @question_id).first
  if @user_answer
    @user_answer.answer_id = @answer_id
    @user_answer.save!
    @message = 'Answer updated successfully!'
  else
    @user.user_answers.create(:question_id => params[:questionId], :answer_id => params[:answerId])
    @message = 'Answer submitted successfully!'
  end
rescue ex
  @message = ex.message.split(':')[1].chomp
end

but according to the page on model association it doesn't look like it's violating this, it looks like it is following along correctly. 但是根据有关模型关联页面,这似乎并没有违反它,它似乎正确地遵循了。 Am I missing something about this? 我是否对此有所遗漏?

The problem lies in directly accessing the variables in the @user_answer object, and not updating the user_answer within the @user variable...and since Rails has an update method, we can do this like so: 问题就出在直接访问变量在@user_answer对象,而不是更新user_answer的内@user变量...既然Rails有一个update的方法,我们可以做到这一点,如下所示:

begin
  @user_answer = @user.user_answers.where(:question_id => @question_id).first
  if @user_answer
    @user.user_answers.update(:question_id => @question_id, :answer_id => @answer_id)
    @message = 'Answer updated successfully!'
  else
    @user.user_answers.create(:question_id => @question_id, :answer_id => @answer_id)
    @message = 'Answer submitted successfully!'
  end
rescue ex
  @message = ex.message.split(':')[1].chomp
end

But we can do better. 但是我们可以做得更好。 Rather than differ by create and update, we can simply use Ruby's short circuit evaluation to create a `@user_answer symbol and update it whether it is new or not. 不必通过创建和更新来区别,我们可以简单地使用Ruby的短路评估来创建一个@user_answer符号并对其进行更新,无论它是否为新的。

begin
  @user_answer = @user.user_answers.where(:question_id => @question_id).first || @user.user_answers.new
  @user_answer.update_attributes!(question_id: @question_id, answer_id: @answer_id)
  @message = 'Answer submitted successfully!'
rescue ex
  @message = ex.message.split(':')[1].chomp
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM