Reputation: 2500
I have a model like this:
class Url < ApplicationRecord
validates ...
before_create :generate_number
def generate_number
self.number = a random value
end
end
and a create()
method in controller:
def create
@url = Url.new(url_params)
respond_to do |format|
if @url.save
format.html { redirect_to @url, notice: 'Url was successfully created.' }
format.json { render :show, status: :created, location: @url }
else
format.html { render :new }
format.json { render json: @url.errors, status: :unprocessable_entity }
end
end
end
My DB only have two fields: given_url
and number
. Now, when I go to the new
page, there's 2 input form for given_url
and number
. But I want number
take the value from generate_number
, not from the form. How can I do that?
Or more specific, is there a way to make the generate_number
method to overrides user's input after the app already receive value from user's input?
Upvotes: 1
Views: 60
Reputation: 23661
You can simply restrict the input from user by using strong params
def url_params
params.require(:url).permit(:other, :params)
end
Upvotes: 1
Reputation: 2500
Well, I have found a way to fix this. As @ts mentioned in the question's comment, I changed before_create :generate_number
to after_create :generate_number
and added self.save
to the end of generate_number
method:
def generate_number
...
self.number = some number
self.save
end
Upvotes: 1