Search code examples
ruby-on-railssimple-form

Automatically populating simple_form fields - RAILS


Let's say I have a Customer and a Brand class (where a customer has many brands and a brand belongs to a customer). When the user is on the show page for a specific customer, he/she has the option to click a button to add a new brand (that button redirects to the form to create a new brand, which contains a field where the user should indicate which customer that brand belongs to). But when the user gets to that form, he/she should not have to manually indicate which customer that brand belongs to, but rather that information should be entered automatically based on the customer_id of the customer whose show page the user was just looking at. If no show page was being looked at, the field for the parent customer_id should be empty (as it is by default) and the user should enter it manually.

Is there a way to implement this in Rails? If so, how?


Solution

  • Your question is a bit hard to understand, but let's go.

    First, you have to create a link to a new brand, something like:

    <%= link_to 'New brand for #{@customer.name}", new_brand_path(customer_id: @customer.id) %>
    

    In this way you are passing the customer_id as a param.

    In the brand controller on the new action you will do

    def new
        @customer = Customer.find_by_id(params[:customer_id])        
        @brand = @customer ? Brand.new(customer_id: @customer.id) : Brand.new
    end
    

    You see that I made an example to make it clear what to do. There are better ways of doing that, but I guess this will guide you through what you want.