在控制器中设置字段

时间:2011-08-19 03:47:08

标签: ruby-on-rails ruby-on-rails-3

创建新Person时,如何设置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在Rails控制台中正常工作。它将'linkable_id'字段设置为1,将'linkable_type'字段设置为'Location'。但是,在提交表单后,将创建Person,但这两个字段保留为空白。

非常感谢任何有关此问题的帮助。

1 个答案:

答案 0 :(得分:3)

您正在新操作中构建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