All threads / How is it done to pass default values in the controller?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

How is it done to pass default values in the controller?

Nicolás Bobb asked in Rails

Some values by default and others by strong parameters from the views

Generally, I put default values in the model itself rather than the controller.

class User
  after_initialize :set_defaults

    def set_defaults
      self.email ||= "[email protected]"
    end
end

I have access to current_user in model ?

I'm try:

def classroom_params
       params.require(:classroom).permit(:name, :owner_id => [current_user])
end

But don't work because "owner.required".

You don't have access to that in the model. For assigning current_user, I do that in the controller but all other defaults I'd put in the model.

def create
  @record = Record.new(record_params)
    @record.owner = current_user

    if @record.save
    #... etc
end

Thanks for all your help!! :)

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 39,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.