2014-04-29 2 views
2

처음에는 영어에 대해 미안하지만 레일스에 대한 지식은 처음 시작한 초보자입니다.중첩 된 양식을 사용할 때 유효성 검사 오류를 표시하는 방법?

CargoItems :

class CargoItem < ActiveRecord::Base 
    belongs_to :cargo 
    attr_accessible :cargo_id, :height, :length, :pieces, :weight, :width 
    validates :cargo, :height, :length, :width, :weight, :pieces, presence: true 
    validates :height, :length, :width, :pieces, numericality: { only_integer: true, greater_than_or_equal_to: 1} 
    validates :weight, numericality: { only_integer: true, greater_than_or_equal_to: 100} 
end 

화물을 :

class Cargo < ActiveRecord::Base 
    belongs_to :airport 
    belongs_to :user 
    belongs_to :cargo_state 
    belongs_to :cargo_price 
    belongs_to :cargo_description 
    has_many :cargo_items, :inverse_of => :cargo, :dependent => :destroy 

    attr_accessible :departure_date, :cargo_state_id, :airport_id, :cargo_price_id, :cargo_description_id, :cargo_items_attributes 
    accepts_nested_attributes_for :cargo_items, :allow_destroy => true, :reject_if => :all_blank 
    validates_associated :cargo_items 
    validates :departure_date, :cargo_state, :airport, :cargo_price, :cargo_description, presence: true 
    validates :departure_date, date: { after: Proc.new { Date.today - 1.day }, before: Proc.new { Time.now + 1.year } }, :on => :create 
    default_scope :order => 'departure_date DESC' 
end 

내가 보석을 다음 사용 simple_forms, nested_forms

나는 관계로이 개 모델을 가지고있다.

<%= simple_nested_form_for @cargo, :wrapper => false do |f| %> 
<%= f.association :airport, :label_method => :full_airport_name, :value_method => :id , :order => :iata_code %> 
<%= f.input :departure_date , as: :date, start_year: Date.today.year, 
end_year: Date.today.year + 16, 
order: [:day, :month, :year] %> 
<%= f.association :cargo_description, :label_method => :description, :value_method => :id, :order => :description %> 
<%= f.association :cargo_price, :label_method => :price, :value_method => :id %> 
<%= f.association :cargo_state, :label_method => :state, :value_method => :id %> 
<hr> 
<table> 
    <tr> 
     <th><%= :length %></th> 
     <th><%= :width %></th> 
     <th><%= :height %></th> 
     <th><%= :weight %></th> 
     <th><%= :pieces %></th> 
    </tr> 
    <%= f.simple_fields_for :cargo_items, @cargo_item do |cargo_items_fields| %> 
    <tr class="fields"> 
     <td><%= cargo_items_fields.text_field :length %></td> 
     <td><%= cargo_items_fields.text_field :width %></td> 
     <td><%= cargo_items_fields.text_field :height %></td> 
     <td><%= cargo_items_fields.text_field :weight %></td> 
     <td><%= cargo_items_fields.text_field :pieces %></td> 
     <td><%= cargo_items_fields.link_to_remove "Remove this item", :confirm => 'Are you sure you want to remove this item?' %></td> 
    </tr> 
    <% end %> 
</table> 
<%= f.link_to_add "Add a item", :cargo_items %> 

<div class="actions"> 
    <%= f.button :submit %> 
</div> 
<% end %> 

화물 컨트롤러 :

내 문제가
def new 
    @cargo = Cargo.new 
    @cargo_item = CargoItem.new 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @cargo } 
    end 
    end 

    def create 
    @cargo = Cargo.new(params[:cargo]) 
    @cargo.user_id = current_user[:id] 

    respond_to do |format| 
     if @cargo.save 
     format.html { redirect_to @cargo, notice: 'Cargo was successfully created.' } 
     format.json { render json: @cargo, status: :created, location: @cargo } 
     else 
     format.html { render action: "new" } 
     format.json { render json: @cargo.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

, 유효성 검사 오류가에 대한 표시되지 않습니다이화물에 속하는 여러 CargoItems 새로운화물을 (그들은 가능성을 동적으로 추가 될 수 있습니다) 추가하는 형태이다 CargoItems, 모델은 실제로 유효성을 검사합니다. 유효성 검사 규칙을 충족하지 않는 CargoItems로화물을 저장할 수 없습니다. 그러나 유효성 확인이 충족되지 않는 경우 Cargo는 저장되지 않으며 CargoItems 필드가 유효하지 않다는 알림없이 동일한 페이지에 머물러 있습니다. 화물 필드 유효성 검사 오류가 제대로 표시됩니다.

고맙습니다.

답변

2

양식 앞에이 오류 알림을 추가해야합니다. 예를 들어 내에서 봐

<% if @author.errors.any? %> 
    <div class="alert alert-block"> 
     <ul> 
      <% @author.errors.full_messages.each do |msg| %> 
       <li><%= msg %></li> 
      <% end %> 
     </ul> 
    </div> 
<% end %> 
<% if @book.errors.any? %> 
    <div class="alert alert-block"> 
     <ul> 
      <% @book.errors.full_messages.each do |msg| %> 
       <li><%= msg %></li> 
      <% end %> 
     </ul> 
    </div> 
<% end %> 

<%= form_for([@author, @book], html: { class: "well" }) do |f| %> 
#labels and buttons... 
<% end %> 

나는 많은 책을 가지고 있으므로 같은 저자가 :

저자 :

class Author < ActiveRecord::Base 
    attr_accessible :name 
    has_many :books, dependent: :destroy 

    accepts_nested_attributes_for :books, allow_destroy: true 

    validates :name, presence: true 
    validates :name, length: { minimum: 3 } 
end 

도서 :

class Book < ActiveRecord::Base 
    attr_accessible :name, :year 
    belongs_to :author 

    validates :name, :year, presence: true 
    validates :year, numericality: { only_integer: true, less_than_or_equal_to: Time.now.year } 
end 
+0

, 그것은 부분적으로 작동합니다. 양식 맨 위에 문제가있는 필드가 표시되지만 필드가 색상으로 강조 표시되지 않습니다. 필드가화물의 부모 형태이므로 필드가 강조 표시되지 않습니다. 단순한 양식 제안 (각 문제 영역을 강조 표시하고이 필드 옆에 각 문제를 표시)과 동일한 알림을받을 수 있습니까? –

+0

다른 답변을 추가했습니다. 도움이된다면 체크 한 것으로 표시하십시오. – jimagic

+1

안녕하세요, 나는이 제안 된 솔루션을 확인할 시간이 있었는데, 그것은 잘 작동합니다. 당신 말이 맞았습니다. "<% if @ cargo.errors.any? %>"그 첫 부분은 양식에 포함되어 있지 않았습니다. 나는 단순한 폼이 부모 폼과 같은 방식으로 중첩 된 폼을 처리 할 것이라고 기대합니다. 여기가 어디입니까? <% if @ cargo.errors.any? %> "건설이 필요하지 않습니다. –

0

간단한 양식 또한 label, hint, input_field, error 및 full_error 도우미를 사용할 수 있습니다. 자세한 내용 문서에 대한 - 오류와>https://github.com/plataformatec/simple_form

예제 코드, 도움을 많이 고맙습니다

<%= simple_form_for @user do |f| %> 
    <%= f.label :username %> 
    <%= f.input_field :username %> 
    <%= f.hint 'No special characters, please!' %> 
    <%= f.error :username, id: 'user_name_error' %> 
    <%= f.full_error :token %> 
    <%= f.submit 'Save' %> 
<% end %> 
+0

미안하지만,이 부분을 이해하지 못했습니다. 중첩 된 양식 대신에 간단한 양식의"중첩 된 양식 "기능을 사용 하시겠습니까? 중첩 된 양식을 선택하면 길게 도움이 될 것입니다. 한 항목 씩 동적으로 항목을 추가 할 수있는 중첩 된 양식을 작성할 수있는 기능을 제공합니다. 간단한 양식으로는이 작업을 수행 할 수 없습니다. –

+0

simple_nested_form_for는 필드 오류와 관련하여 simple_form_for와 동일한 기능을 수행합니다. – jimagic

관련 문제