I have Bands and Codes and Users.
the key/codes will let a user do things with the band. I am on the Band#show action and need to generate a code, and then have that code be related to the user and the band.
so:
Code belongs_to :band, belongs_to :user
Band has_many :codes
User has_many :codes
So now I need to use a form_for (I think) to create a button which when pressed does the following:
check if a user has a code with that band(user can have one code per band)
If not:
- Creates a 6 digit alphanumeric key/code (I know ActiveSupport can do
it: <%= SecureRandom.hex(3)%> but this needs to be in the model or
controller) - Set the correct associations, this code works for this user and this band. I am using Devise so I have access to a current_user method
- and return the user to the Band#show
action
If the user already has a code for that band, then they are given an error “You already have a code”
I want to eventually make this call with Ajax to keep from reloading the page but for now I am just trying to build the function.
First off, I would create the following route in your routes.rb:
This will create an additional route looking like this:
Then from your views you can use the button_to helper method to send a post request like this:
When the user clicks on that button then you can handle the rest from the controller action like this:
Lastly, the actual randomized code I would generate from a before_create callback from the Code model itself, like this:
Then if you think it’s necessary then you could also add other verifications like only showing the Add Code button if there is no Code existing or perhaps add error messages if a user tries to add another code for the same band, but I leave that to you. The button_to helper also supports Ajax by using
:remote => trueso you can further develop it the way you want.