Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aya-soft/5c62ef8f26c7a911507f99748971fc09 to your computer and use it in GitHub Desktop.
Save aya-soft/5c62ef8f26c7a911507f99748971fc09 to your computer and use it in GitHub Desktop.
Unless не используют с else, т.к. он и так трудно понятный, а тут станет вообще ненужным, потому что его можно легко превратить в легко понимаемый if-else
def new
unless current_user.service_station.present?
redirect_to new_profile_service_station_path
else
service = current_user.service_station.service_station_comments.where("spare_id = ?", params[:spare_id])
if service.present?
redirect_to "/profile/service_station_comments/#{service.first.id}/edit"
end
@comment = ServiceStationComment.new
gon.labor_times_price = current_user.service_station.labor_times_price
end
end
@aya-soft
Copy link
Author

aya-soft commented May 27, 2016

Тут можно поступить двумя способами:

  1. Если хочется сразу редирект при неблагоприятных условиях, то можно так:
redirect_to new_profile_service_station_path unless current_user.service_station and return
# а потом все остальное безо всяких else, потому что и так понятно, что если первое условие не сработало, то СЕРВИС есть!!!

@aya-soft
Copy link
Author

aya-soft commented May 27, 2016

Метод .present? используют только когда хотят проверить ПРИСУТСТВИЕ каких либо данных!!!

obj.present? == !obj.blank?
nil.present? # => false
"".present? # => false
[].present? # => false

Если хочется проверить ссылку на объект, то используют просто эту ссылку:

if current_user.service_station # будет true, если есть объект, будет false, если current_user.service_station вернет nil

@aya-soft
Copy link
Author

aya-soft commented May 27, 2016

service = current_user.service_station.service_station_comments.where("spare_id = ?", params[:spare_id])

Почему ты назвал переменную service, когда ты достаешь из базы коментарИИ, т.е. и имя неправильное и множественное число должно быть!

@aya-soft
Copy link
Author

aya-soft commented May 27, 2016

Еще по этому:

      service = current_user.service_station.service_station_comments.where("spare_id = ?", params[:spare_id])
      if service.present?
        redirect_to "/profile/service_station_comments/#{service.first.id}/edit"
      end

Ты же знаешь, что для одной запчасти может быть только один комментарий от одного сервиса!

Тогда зачем сначала выбирать по where, а потом делать first???

Можно же сразу так:

@existing_comment = current_user.service_station.service_station_comments.find_by(spare_id: params[:spare_id])

@aya-soft
Copy link
Author

Еще по этому:

      service = current_user.service_station.service_station_comments.where("spare_id = ?", params[:spare_id])
      if service.present?
        redirect_to "/profile/service_station_comments/#{service.first.id}/edit"
      end
  1. Как уже говорил вместо if service.present? достаточно просто if service

  2. Ты забыл как url-хелперы делать? Огород городишь :(

# ВМЕСТО
      if service.present?
        redirect_to "/profile/service_station_comments/#{service.first.id}/edit"
      end
# НАДО
redirect_to edit_profile_service_station_comments(@existing_comment) if @existing_comment and return

@romhi
Copy link

romhi commented May 30, 2016

def new
if current_user.service_station
@existing_comment = current_user.service_station.service_station_comments.find_by_spare_id(params[:spare_id])
if @existing_comment
redirect_to edit_profile_service_station_comment_path(@existing_comment.id)
end
@comment = ServiceStationComment.new
@labor_times_price = current_user.service_station.labor_times_price
else
redirect_to new_profile_service_station_path, notice: "Сначала добавьте автосервис!"
end
end

@romhi
Copy link

romhi commented May 30, 2016

Когда выполняется and return продолжается выполнение кода в текущем контроллере, что нам не нужно, т.к. у нас переменная comment будет nil, потому что не может быть комментариев у несуществующего автосервиса. Финал привожу
def new
if current_user.service_station
@existing_comment = current_user.service_station.service_station_comments.find_by_spare_id(params[:spare_id])
redirect_to edit_profile_service_station_comment_path(@existing_comment) if @existing_comment
@comment = ServiceStationComment.new
@labor_times_price = current_user.service_station.labor_times_price
else
redirect_to new_profile_service_station_path, notice: "Сначала добавьте автосервис!"
end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment