hellomello
hellomello

Reputation: 8585

Ruby on Rails: Insert value into database based on user input?

I have an address column, but I'm not using :address in my form, instead, I have

:street, :state, :city, :zip columns:

<%= form_for @user, :html => {:multipart => true} do |f| %>
    <%= f.label :street %>
    <%= f.text_field :street %>

    <%= f.label :state %>
    <%= f.text_field :state %>

    <%= f.label :city %>
    <%= f.text_field :city %>

    <%= f.label :zip %>
    <%= f.text_field :zip %>

    <%= f.submit %>
<% end %>

Because I don't have a field for :address, but I would like to compile the information in the form and still insert it into my database. For example

(12345 Maple St, Made City CA 90017 or maybe when I get more advanced, I'll use some gem to compile the given information and put into a correct address format.)

How do I do such a thing?

My controller looks something like this:

  def create
    @user = User.new(params[:user])
    if @user.save
        redirect_to @user, notice: "Successfully created."
    else
      render :action => 'edit'
    end
  end

Upvotes: 2

Views: 4562

Answers (3)

zeantsoi
zeantsoi

Reputation: 26193

Unless processing overhead is a major concern, you're breaking Rails' DRY principles by saving concatenated model attributes as a separate attribute.

The Rails Way of accomplishing this would be to create a model convenience method that concatenates existing attributes into a pseudo-address attribute without requiring any additional attributes be committed to the database:

# my_model.rb
def address
    [street, city, state, zip].join(', ')
end

# my_view.html.erb
<%= @user.address %>

Alternatively, if you only need the full address for display in your views, you might consider using a view helper:

# app/helpers/my_model_helper.rb
module MyModelHelper
    def formatted_address(address)
        [address.street, address.city, address.state, address.zip].join(', ')
    end
end

# my_view.html.erb
<%= formatted_address(@address) %>

Upvotes: 1

usha
usha

Reputation: 29349

Another option would be to do it in model

attr_accessor :street, :city, :state, :zip

before_create :concate_address_attrs

Edit:-

I feel before_save is better to use over before_create

before_save :concate_address_attrs

def concat_address_attrs
  self.address = [street, city, state, zip].join(", ")
end

Upvotes: 1

usha
usha

Reputation: 29349

    def create
            address = [params[:user].delete(:street), params[:user].delete(:state), params[:user].delete(:city), params[:user].delete(:zip)].join(", ")
            @user = User.new(params[:user].merge(:address => address))
            if @user.save
                redirect_to @user, notice: "Successfully created."
            else
              render :action => 'edit'
            end
        end

Upvotes: 2

Related Questions