在控制器中设置字段
问题描述:
创建新人时,如何设置未包含在new.html.erb表单中的字段?在控制器中设置字段
这里是控制器和形状:
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 %>
这里有机型:
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
的关联方法@person = location.persons.build工作在滑轨控制台细。它将'linkable_id'字段设置为1,将'linkable_type'字段设置为'位置'。但是,在提交表单后,Person被创建,但这两个字段留空。
任何有关这个问题的帮助将不胜感激。
答
您正在新行动中构建人物对象。你必须建立相同的创建操作以及..
def create
# location = Calculate location here
@person = location.persons.build(params[:person])
if @person.save
flash[:success] = "Person added successfully"
redirect_to account_path(params[:account_id])
else
render 'new'
end
end
不要忘记添加PARAMS通过形式'location.persons.build(PARAMS [:人])发送' – DanneManne
我如何从表单提交中计算位置? –
您必须使用如下隐藏变量在表单中设置位置信息:f.hidden_field:linkable_id –