[RUBY] Prevent login users from transitioning to a specific page by entering a URL

【Overview】

1. Conclusion </ b>

2. When does it happen </ b>

3. How to use </ b>

4. What I learned from here </ b>

  1. Conclusion

Use “redirect_to” and “unless” </ b>!

  1. When does it happen

buy_item_controller.rb


  def edit
    @buy_item = BuyItem.find(params[:id])
  end

For example I think I program the "edit" action when editing my page, my account, or the page I posted.

At this time, with the above program alone, if you type ~ ~ / ~ ~ / edit in the URL, even the logged out user or the user logged in to the same application can operate different accounts.


3. How to use

buy_item_controller.rb


def edit
    @buy_item = BuyItem.find(params[:id])
   redirect_to root_path unless current_user.id == @buy_item.user_id
end

Since we are using gem "devise", "current_user.id" is included.

"Redirect_to root_path" is used to "return to the top page".

"Unless current_user.id == @ buy_item.user_id" is programmed as "if the currently logged-in user is not the seller user of the item".

Therefore, if the seller and the logged-in user are different, you cannot edit the item.


4. What I learned from here

I thought I would set it with "edit" even if I was logged out. However, if you are logged out, the range is too far and you have to set it for all actions. At that time, I remembered before_action. Actions that do not cause an infinite loop using before_action and except Other than (excluding index and show), I thought that programming should be done unless.

buy_item_controller.rb


 before_action :move_to_index, except: [:index, :show]

  def move_to_index
    redirect_to new_user_session_path unless user_signed_in?
  end