最后我能够解决这个问题
我尝试在 Ruby on Rails 4 中实现表单对象模式,但我找不到我的错误。
我为电话簿构建了一个示例应用程序,其中包括以下模型
人
- 名
- 姓
电话号码
- 数字
电子邮件
- 地址
[编辑]
感谢@sockmonk,我可以解决这段代码中的一个问题。仍然无法正常工作...
这是我使用的代码
# app/models/person.rb
class Person < ActiveRecord::Base
has_many :phone_numbers
has_many :emails
end
# app/controllers/people_controller.rb
class PeopleController < ApplicationController
def new
@person_form = PersonForm.new
end
def create
@person_form = PersonForm.new(person_form_params)
@person_form.save
redirect_to person_path(@person)
end
def index
@people = Person.all
end
def show
@person= Person.find(params[:id])
end
private
def person_form_params
params.require(:person_form).permit(:person_first_name, :person_last_name, :phone_number_number, :email_address)
end
end
# app/forms/person_form.rb
class PersonForm
include Virtus
include ActiveModel::Model
# extend ActiveModel::Naming
# include ActiveModel::Conversion
# include ActiveModel::Validations
attr_reader :person
attr_reader :phone_number
attr_reader :email
attribute :person_first_name, String
attribute :person_last_name, String
attribute :phone_number_number, Integer
attribute :email_address, String
def persisted?
false
end
def save
if valid?
persist
true
else
false
end
end
private
def persist
@person = Person.create(first_name: person_first_name, last_name: person_last_name)
@phone_number = @person.phone_numbers.create(number: phone_number_number)
@email = @person.emails.create(address: email_address)
end
end
# app/views/people/new.html.erb
<h1>New Person</h1>
<%= form_for :person_form do |f| %>
<p>
<%= f.label :person_first_name %> </ br>
<%= f.text_field :person_first_name %>
<p>
<%= f.label :person_last_name %> </ br>
<%= f.text_field :person_last_name %>
<p>
<%= f.label :phone_number_number %> </ br>
<%= f.text_field :phone_number_number %>
<p>
<%= f.label :email_address %> </ br>
<%= f.text_field :email_address %>
<% end %>
(在https://github.com/speendo/Phonebook2找到整个代码)
顺便提一句。您可能已经注意到,我在这段代码中使用了Virtus——不知道这是否重要。
如果您需要任何其他信息,请随时告诉我。