0

I have a customer model that belongs to user. However, when creating the new customer, the user will not be signed in. Instead I will be assigning the user based on his name attribute.
Here is the customer migration:

create_table :customers do |t|
  t.belongs_to :user
  t.string :name, null: false
  t.date :install_date, null: false
  t.decimal :mmr, null: false
  t.boolean :sixty_month, default: false
  t.boolean :eft, default: false
  t.boolean :activation, default: false

  t.timestamps
end

I then have a new customer form:

<h1>Create Customer</h1>

<%= form_for @customer do |f| %>
  <div>
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>

  <div>
    <%= f.label :install_date %>
    <%= f.date_field :install_date %>
  </div>

  <div>
    <%= f.label :mmr %>
    <%= f.number_field :mmr %>
  </div>

  <div>
    <%= f.label :sixty_month %>
    <%= f.check_box :sixty_month %>
  </div>

  <div>
    <%= f.label :eft %>
    <%= f.check_box :eft %>
  </div>

  <div>
    <%= f.label :activation %>
    <%= f.check_box :activation %>
  </div>

  <div>
    <%= f.label :users_name %>
    <%= f.text_field :users_name %>
  </div>

  <%= f.submit 'Create Customer' %>
<% end %>

I need to get the users_name field and match it with the associated user and take that users id and assign it to the customers :user_id attribute. In the customers controllers create action so far I have:

@customer.user_id = User.where("name = #{}").id

I need to pull to input from the users_name field in the new customer form and put it into the above code somehow. I just don't know how haha. All help is appreciated!

1 Answer 1

1

You will probably want to move this out of the controller and into a helper method but you could do like this:

    def create
      @customer = Customer.new(customer_params)
        if params[:users_name]
          user = User.find_by(name: params[:users_name])
          @customer.user_id = user.id unless user.nil?
        end
       if @customer.save
         flash[:success] = "Customer created!"
         redirect_to @customer
       else
        render 'new'
       end
    end

This is assuming you are using Rails 4.

Sign up to request clarification or add additional context in comments.

3 Comments

Customer.find_by(name: params[:users_name]).id will raise a `NoMethodError: undefined method id' for nil:NilClass if a matching record is not found (tested under rails-4.1.8).
I think that there is a syntax error up there, an extra parenthesis after the first if line with params
I ended up also having to change my :users_name field in the create customer form to text_field_tag in place of f.text_field because the customer has no users_name column.

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.