class RailsBestPractices::Reviews::UseModelAssociationReview

review a controller file to make sure to use model association instead of foreign key id assignment.

See the best practice details here rails-bestpractices.com/posts/2010/07/19/use-model-association/

Implementation:

Review process:

check model define nodes in all controller files,
if there is an attribute assignment node with message xxx_id=,
and after it, there is a call node with message "save" or "save!",
and the receivers of attribute assignment node and call node are the same,
then model association should be used instead of xxx_id assignment.

Private Instance Methods

attribute_assignment(node) click to toggle source

check an attribute assignment node, if its message is xxx_id, then remember the receiver of the attribute assignment in @assignments.

# File lib/rails_best_practices/reviews/use_model_association_review.rb, line 48
def attribute_assignment(node)
  if node.left_value.message.is_a?(Sexp) && node.left_value.message.to_s =~ /_id$/
    receiver = node.left_value.receiver.to_s
    @assignments[receiver] = true
  end
end
call_assignment(node) click to toggle source

check a call node with message “save” or “save!”, if the receiver of call node exists in @assignments, then the attribute assignment should be replaced by using model association.

# File lib/rails_best_practices/reviews/use_model_association_review.rb, line 58
def call_assignment(node)
  if ['save', 'save!'].include? node.message.to_s
    receiver = node.receiver.to_s
    add_error "use model association (for #{receiver})" if @assignments[receiver]
  end
end