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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With