If you don't want to create two separate address fields altogether, you can pass the same address
argument to each of two tag helpers as an array:
<%= f.text_field_tag 'address[]' %>
<%= f.text_field_tag 'address[]' %>
Then, in your controller, you can access the respective values of each of the two fields as members of an array:
address_array = params[:address]
address_string = address_array[0] + ', ' + address_array[1] # Assigns comma delimited string
Thereafter, you can pass address_string
as the value for the address
attribute of your model.
If you don't want to change your model schema, there's considerable upside to this approach since you can use your address
attribute as-is – all you're doing is modifying how the field is treated in the form, and then processing the return values in your controller accordingly.
UPDATE:
The params
hash can be modified in-place such that params[:info][:address]
reflects your custom string, rather than an array of two string:
def create
address_array = params[:address]
address_string = address_array[0] + ', ' + address_array[1]
params[:info][:address] = address_string # Assigns `address_string` to `params[:info][:address]`
# remainder of the `create` logic
end
UPDATE 2:
Your new
and create
controller actions should look something akin to this:
def new
@info = Info.new
end
def create
address_array = params[:address]
address_string = address_array[0] + ', ' + address_array[1]
params[:info][:address] = address_string
respond_to do |format|
# First, instantiate a new instance of `Info`
@info = Info.new(params[:info])
# Then, save
if @info.save
format.html { redirect_to @info, notice: 'Info was successfully created.' }
format.json { render action: 'show', status: :created, info: @info }
else
format.html { render action: 'new' }
format.json { render json: @info.errors, status: :unprocessable_entity }
end
end
end
UPDATE 3:
If you're having issues modifying the params
hash in place, you may want to try assigning the address
attribute directly:
def create
address_array = params[:address]
address_string = address_array[0] + ', ' + address_array[1]
respond_to do |format|
@info = Info.new(params[:info])
@info.address = address_string # Assign attribute directly
if @info.save
# remainder of code