Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to the form a virtual fields


Starting to learn the Ruby on Rails.
How to add to the form a virtual fields?
After submitting the form, these fields must be combined and stored in a single database field.

like image 623
Yuri Malov Avatar asked Sep 27 '14 17:09

Yuri Malov


1 Answers

First set up your form as usual:

<%= form_for @user do |f| %>
<ol>
  <li>
    <%= f.label :first_name, 'First Name' %>
    <%= f.text_field :first_name %>
  </li>
  <li>
    <%= f.label :last_name, 'Last Name' %>
    <%= f.text_field :last_name %>
  </li>
  <%= f.submit %>
</ol>
<% end %>

In this example we are adding a virtual attribute for first_name and last_name.

user.rb

class User < ActiveRecord::Base
  attr_accessor :first_name
  attr_accessor :last_name
end

Add an attr_accessor for your new virtual attribute.

users_controller.rb

def create
  @user = User.new(:full_name => {'firstname' => user_params[:first_name], 'lastname' => user_params[:last_name]})
  ...
end

private

def user_params
  params.require(:user).permit(:first_name, :last_name)
end

Finally, add a method to permit the virtual attribute params (assuming Rails 4).

To save multiple inputs and save them into a single field in the DB you can combine the virtual fields in the controller and then save them to the DB, as shown in the create method above.

like image 79
Tom Kadwill Avatar answered Oct 01 '22 13:10

Tom Kadwill