gpt4 book ai didi

ruby-on-rails - 在 Controller 中设置字段

转载 作者:行者123 更新时间:2023-12-04 06:08:42 25 4
gpt4 key购买 nike

新建Person时,如何设置new.html.erb表单中没有的字段?

这是 Controller 和表单:

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,但这两个字段留空。

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

最佳答案

您正在新操作中构建人员对象。您还必须在创建操作中构建相同的内容..

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

关于ruby-on-rails - 在 Controller 中设置字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7116732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com