1

저는 루비를 처음 접했고 주문에 항목을 추가 할 수있는 양식을 작성하려고합니다. 양식은 주문의 각 항목에 대해 수량을 가져와야합니다.다음을 기반으로 양식 만들기 : has_many through relationship relationship

class Order < ActiveRecord::Base 
    belongs_to :restaurant 
    has_many :selections 
    has_many :items, :through =>:selections; 
end 

class Selection < ActiveRecord::Base 
    belongs_to :order 
    belongs_to :item 
end 

class Item < ActiveRecord::Base 
    belongs_to :menu 
    has_many :selections 
    has_many :orders, :through => :selections 
end 

class Restaurant < ActiveRecord::Base 
    has_many :orders 
    has_many :menus 
    has_many :items, :through => :menus 
end 

class Menu < ActiveRecord::Base 
    belongs_to :restaurant 
    has_many :items 
end 

순서 제어기

# GET /orders/new 
def new 
    @order = Order.new 
    @restaurant.items.all.each do |item| 
    @order.selections.build 
    end 
end 

주문/_form.html.erb은 :

양식은 사용 가능한 항목을 나열하고 당신을 위해 수량을 입력 할 수 있도록되어있다 아이템.

<%= form_for [@restaurant,@order], :html => { :class => 'form-horizontal' } do |f| %> 
    <div class="control-group"> 
     <%= f.label :current_table, :class => 'control-label' %> 
     <div class="controls"> 
     <%= f.text_field :current_table, :class => 'text_field' %> 
     </div> 
    </div> 

    <% f.fields_for :selections do |ff| %> 
     <div class="control-group"> 
      <%= ff.label :quantity, :class => 'control-label' %> 
      <div class="controls"> 
      <%= ff.text_field :quantity, :class => 'text_field' %> 
      </div> 
     </div> 
    <% end%> 

    <div class="form-actions"> 
     <%= f.submit nil, :class => 'btn btn-primary' %> 
     <%= link_to t('.cancel', :default => t("helpers.links.cancel")), 
        course_orders_path, :class => 'btn' %> 
    </div> 
<% end %> 

나는 다음과 같은 오류 얻을 페이지를 렌더링 할 때 :

undefined method `quantity' for 
<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Selection:0x007ffa0287cd60> 

을 나는 어떤 선택을 초기화하지 않은하지만 난 완전히 확실하지 않다 때문에 이것은 아마도 실현 방법/어디 나는 그렇게해야한다. 양식이 제출되면 비어 있지 않은 수량 각각에 대해 선택 항목을 작성하려고합니다.

그래서 첫 번째 질문은 내가 알고있는 각 항목에 대해 수량을 가질 수 있도록 양식을 구성하는 방법입니다.

이 작업을하려면 주문 컨트롤러에서 무엇인가를 초기화해야합니까?

주문 컨트롤러의 작성 방법을 설정하는 방법을 알려주는 자습서를 알려줄 수 있습니까?

편집 :

은 내가 페이지를 렌더링 할 때 그래서 더 이상 오류가 발생하지 않습니다,하지만 내 '선택'필드 중 어느 것도 렌더링되지, 주문 컨트롤러와 폼에 몇 가지 코드를 추가했다. 일부 로깅 및 디버거를 사용하여 4 가지 선택 항목을 올바르게 빌드 했으므로 해당 양식 요소가 표시 될 것으로 예상됩니다.

모든 아이디어를 얻을 수 있습니다.

+1

그런 짓을했다 '@의 order.selections'은 아마 당신이 (- 선택 아마도 하나 개의 모델에 대해 정의) 숙박 시설의 얻을 수, 배열입니다. 또한 레스토랑 모델을 게시하여 종속성을 명확히하십시오. – zishe

+0

식당 및 메뉴 모델을 추가했습니다. –

+1

레스토랑 메뉴에 'has_many : orders'가없는 이유는 무엇입니까? –

답변

0

당신은 어딘가에

accepts_nested_attributes_for :nested_class 

누락?

또한, 나는

<%= form_for [@restaurant,@order] do |f| %> 
... 
    <%= f.fields_for :selections, @order.selections do |ff| %> 
    ... 
    <% end %> 
... 
<% end %>