#Bad writing
@incorrect_questions = session[:incorrect_question_ids].map { |n| Question.find(n.to_i) }
#Why not?
#If this is the case, a query that calls the Question will be issued for each number of cases, and if there are 100, 100 queries will be issued, so this is better.
#Good writing
@incorrect_questions = Question.where(id: session[:incorrect_question_ids].map(&:to_i))
Rails way of thinking
-DHH's opinion is that it is better to use a different controller for actions that do not exist by default, and I think so too. ・ What is REST? ・ One of the object-oriented ideas is that an object has its own state. ・ It is dangerous to use session, so why not prepare the person's condition at the table? ・ Avoid the name Test ◯◯ as it may be mistaken for an rspec file. -Since the method runs unintentionally in the callback system (before_save etc.), it is not very preferable to write the logic there.
#Bad writing
def index
@questions = Question.all
end
#Why no?
#I think that there is no problem with the current number, but if you use all in the actual service, you should be careful because memory may be insufficient and it may drop.
Basically, dynamically changing data (for example, user-added data) is select/I think it is better to make a habit of limiting the required columns with pluck etc.
#Bad writing
<%= form_for(@question_similar, url: { controller: 'question_similar', action: 'create' }) do |f| %>
#Reasons not good
url: {〜〜〜}Is xxx_It seems that you can write with path
#Bad writing
def cancel_save
question_similars.each do |question_similar|
if question_similar.similar_word == ""
question_similar.delete
end
end
end
#.Use blank
#Transaction okay?
#delete_I think all has better performance
params[:front_article_search_form][:heart_period]
This kind of hash is called a two-dimensional hash, If params [: front_article_search_form] is nil in the first place Errors like undefined method `[]'for nil: NilClass (NoMethodError) often occur. So you have to be careful about how to write it.
If it was me
article_search_form = params[:front_article_search_form]
if article_search_form.present?
@heart_period = article_search_form[:heart_period]
end
Recommended Posts