1

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?

7
  • 1
    First you could remove the input from the form, if you are not interested in the user's input. Then you have to remove the field from the strong parameters whitelist. But actually: Since the generate_number is always called before create, it would override the user's input anyway. Commented Feb 6, 2017 at 12:53
  • 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? Commented Feb 6, 2017 at 13:00
  • you can use after_create for that. every time you submit form user input is overrides with your random value generate number Commented Feb 6, 2017 at 13:08
  • I tried but it did not works Commented Feb 6, 2017 at 13:10
  • 1
    Over-riding a specific attribute should work using a before_save also. in the model. before_save :override_number def override_number self.number = <some random number here> end. Can you see if you are getting some errors or if some other code is getting executed. try using pry gem to debug Commented Feb 6, 2017 at 13:12

2 Answers 2

1

You can simply restrict the input from user by using strong params

def url_params
  params.require(:url).permit(:other, :params)
end
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.