2014-06-12 84 views
0

Im在Rails 4中與嵌套表單掙扎,這是我第一次做出這種形式。我已經閱讀了很多文檔,但我無法使其工作。 :-(在Rails 4.0.3中嵌套的表格

我有兩個車型:人與疾病的一個人可以有許多疾病和一個病屬於人看起來很簡單的疾病形式不保存在數據庫中

人。型號:

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+\-.][email protected][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 %> 

非常感謝你的幫助。

+0

我忘了說,沒有在模型驗證仍然不起作用。 – user3402629

+0

我的答案是否適合你? – Pavan

回答

1

的問題是與線<%= simple_fields_for :diseases do |my_disease| %>。它應該是

<%= f.simple_fields_for :diseases do |my_disease| %> 

這應該工作。

<%= simple_form_for @person do |f| %> 

    <%= f.input :name %> 
    <%= f.input :email %> 

    <%= f.simple_fields_for :diseases do |my_disease| %> #here 
     <%= my_disease.input :description %> 
    <% end %> 

    <%= f.button :submit %> 
<% end %> 

欲瞭解更多信息,請參閱本API

+0

是的,這是問題...我昨天整天都在努力修復它......非常尷尬。謝謝! – user3402629

+0

@ user3402629很高興幫助:) – Pavan