Damir Nurgaliev
Damir Nurgaliev

Reputation: 351

How to set field automatically in Rails

I have a simple feedback form to allow the Users send the feedback. Controller for it:

class FeedbacksController < ApplicationController
  expose(:feedback, attributes: :feedback_params)

  def create
    ApplicationMailer.customer_feedback(feedback).deliver_now if feedback.save

    respond_with(feedback, location: root_path)
  end

  private

  def feedback_params
    params.require(:feedback).permit(:email, :message, :name, :phone)
  end
end

Here I'm using expose gem. And the view for it:

= simple_form_for(feedback, url: feedback_path) do |f|

      legend
        = t(".any_questions")

      .form-inputs
        = f.input :name
        = f.input :email
        = f.input :phone
        = f.input :message, as: :text

      .form-actions
        = f.button :submit, t(".submit")

I want the next: to check somewhere if current user present(logged in to application) If yes = then set the email field using user.email (when he visit the feedback form -> email should be already filled in. If user not logged in to site then this field should be empty. Where should I put this logic? Thanks!

Upvotes: 0

Views: 28

Answers (1)

Haley Mnatzaganian
Haley Mnatzaganian

Reputation: 194

The simple form documentation explains how simple form is very easy to customize according to your needs. Assuming you are using devise for user authentication (if you're not, simple_form is designed to work with devise so you should check it out), then you can user current_user to access the currently logged in user.

I think simple_form's input_html would help you here:

= f.input :email, input_html: { value: "#{current_user.email if current_user}"}

Upvotes: 2

Related Questions