When creating a new Person, how do I set its fields that are not included in the new.html.erb form?
Here is the controller and form:
class PeopleController < ApplicationController
def new
@account = Account.find_by_id(params[:account_id])
organization = @account.organizations.primary.first
location = organization.locations.primary.first
@person = location.persons.build
end
def create
@person = Person.new(params[:person])
if @person.save
flash[:success] = "Person added successfully"
redirect_to account_path(params[:account_id])
else
render 'new'
end
end
end
<h2>Account: <%= @account.organizations.primary.first.name %></h2>
<%= form_for @person do |f| %>
<%= f.label :first_name %><br />
<%= f.text_field :first_name %><br />
<%= f.label :last_name %><br />
<%= f.text_field :last_name %><br />
<%= f.label :email1 %><br />
<%= f.text_field :email1 %><br />
<%= f.label :home_phone %><br />
<%= f.text_field :home_phone %><br />
<%= f.submit "Add person" %>
<% end %>
Here are the models:
class Location < ActiveRecord::Base
belongs_to :organization
has_many :persons, :as => :linkable
has_one :address, :as => :addressable
scope :primary, where('locations.primary_location = ?', true)
accepts_nested_attributes_for :address
end
class Person < ActiveRecord::Base
belongs_to :linkable, :polymorphic => true
end
The association method @person = location.persons.build works fine in the Rails Console. It sets the ‘linkable_id’ field to 1 and the ‘linkable_type’ field to ‘Location’. However, after submitting the form the Person is created but these two fields are left blank.
Any help with this problem will be greatly appreciated.
You are building the person object in the new action. You have to build the same in the create action as well..