【发布时间】:2014-06-12 08:59:12
【问题描述】:
我正在为 Rails 4 中的嵌套表单苦苦挣扎,这是我第一次制作这种表单。我已经阅读了很多文档,但我无法使其工作。 :-(
我有两个模型:Person 和 Disease。一个人可以有多种疾病,一种疾病属于一个人。看起来很简单。疾病表格未保存在数据库中。
人物模型:
class Person < ActiveRecord::Base
belongs_to :user
has_many :diseases, :dependent => :destroy #if you delete a person you also delete all diseases related
has_many :appointments, :dependent => :destroy
validates_presence_of :name, :email
validates :name, :length => {:maximum => 50, :too_long => "name is too long"}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, format: { :with => VALID_EMAIL_REGEX , message: "is invalid" }
accepts_nested_attributes_for :diseases
end
疾病模型:
class Disease < ActiveRecord::Base
belongs_to :person
has_many :treatments
validates_presence_of :name, :start
validates :name, :length => {:maximum => 50, :too_long => "is too long, you can use the description field"}
validate :start_must_be_before_end, :unless => [:chronical, :unfinished], :presence => true
validates :end, :presence => true, :unless => [:chronical, :unfinished], :presence => true
validates :description, :length => {:maximum => 5000, :too_long => "is too long"}
def start_must_be_before_end
if self[:end] < self[:start]
errors.add(:start, "must be before end time")
return false
else
return true
end
end
end
人员控制器:
def create
current_user
@person = Person.new(person_params)
@person.user_id = @current_user.id
respond_to do |format|
if @person.save
format.html { redirect_to @person, notice: 'Person was successfully created.' }
format.json { render action: 'show', status: :created, location: @person }
else
format.html { render action: 'new' }
format.json { render json: @person.errors, status: :unprocessable_entity }
end
end
end
def person_params
params.require(:person).permit(:name, :surname, :gender, :birthdate, :bloodtype, :user_id, :phone, :email, diseases_attributes: [:id, :description] )
end
表格:
<%= simple_form_for @person do |f| %>
<%= f.input :name %>
<%= f.input :email %>
<%= simple_fields_for :diseases do |my_disease| %>
<%= my_disease.input :description %>
<% end %>
<%= f.button :submit %>
<% end %>
非常感谢您的帮助。
【问题讨论】:
-
我忘了说没有模型中的验证仍然无法工作。
-
我的回答对你有用吗?
标签: ruby-on-rails forms nested