I will write it as a memorandum when creating my own portfolio. This time, I will describe the function of the flag and the title using it. Since I am a beginner, please point out any mistakes or catches.
--About flags --How to set a flag --Flag switching --Implementation of a function that switches the logical value when a link is clicked
It is an attribute that takes a logical value, and conditional branching can be created depending on whether this value is true or false. Example) Add the admin attribute, which is information about whether the user is an administrator, to the user model. (Admin flag) Then You will be able to use the admin? method. You can use this to determine if a user is an administrator. The code below is true for administrators and false for non-users.
#current_Whether user is an administrator
current_user.admin?
Add attributes to the model. In my portfolio, I decided to flag the User model as complete to determine if the user achieved the goal.
$ rails generate migration add_complete_to_users complete:boolean
The default value is false, so add default: false to the migration file.
class AddCompleteToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :complete, :boolean, default: false
end
end
$ rails db:migrate
Now you have added the complete flag.
In my portfolio, I wanted complete to be true when I clicked on the goal achievement link, so I decided to create a method that would change the false of the complete attribute to true. The method name is derived from the function of my portfolio.
#Toggle the complete flag
def congratulations
current_user.toggle(:complete)
current_user.save!
end
I used toggle to invert the truth of the complete attribute, which is an argument. And it is saved by the save! method. Now you have a method to switch flags. In addition, I wrote the above method in users_controller.rb.
Write the code below in the view.
<%= link_to 'Goal achievement' , controller: :users, action: :congratulations %>
Now when you click the goal achievement link, the users controller's congratulations action (the truth-inverted method created above) will be executed. All you have to do is create the target view, set the route, and you're done.
This is Qiita's first post. I realized the importance of output. In particular, I was worried about how to implement the function implemented this time and what method to use for a long time, so I decided to write it without forgetting.
Recommended Posts