2017-01-31 8 views
0

sale.rb "부모"중첩 된 fields_for 형태의 레일을 객체 5

class Sale < ActiveRecord::Base 
    has_many :branch_history_solds 
    accepts_nested_attributes_for :branch_history_solds, :reject_if => lambda { |a| a[:content].blank? }, 
           :allow_destroy => true 
end 

class SalesController < ApplicationController 
    before_action :set_sale, only: [:show, :edit, :update, :destroy] 

    # GET /sales 
    # GET /sales.json 
    def index 
    @sales = Sale.all 
    end 

    # GET /sales/1 
    # GET /sales/1.json 
    def show 
    end 

    # GET /sales/new 
    def new 
    @sale = Sale.new 
    @sale.branch_history_solds.build 
    end 

    # GET /sales/1/edit 
    def edit 
    end 

    # POST /sales 
    # POST /sales.json 
    def create 
    @sale = Sale.create(sale_params) 
    # @sale.branch_history_solds.build 

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

    # PATCH/PUT /sales/1 
    # PATCH/PUT /sales/1.json 
    def update 
    @sale = Sale.find(params[:id]) 

    respond_to do |format| 
     if @sale.update_attributes(sale_params) 
     format.html { redirect_to @sale, notice: 'Sale was successfully updated.' } 
     format.json { render :show, status: :ok, location: @sale } 
     else 
     format.html { render :edit } 
     format.json { render json: @sale.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /sales/1 
    # DELETE /sales/1.json 
    def destroy 
    @sale.destroy 
    respond_to do |format| 
     format.html { redirect_to sales_url, notice: 'Sale was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_sale 
     @sale = Sale.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def sale_params 
     params.require(:sale).permit(:receipt_no, :customer_name, :phone_number, :email, :branch_id, :paid, branch_history_sold_attributes: [:id, :sold, :branch_product_id]) 
    end 
end 

branch_history_sold.rb "아이"

class BranchHistorySold < ActiveRecord::Base 
    belongs_to :sale 

end 

class BranchHistorySoldsController < ApplicationController 

    def index 
    @search = BranchHistorySold.ransack(params[:q]) 
    @branch_sold_histories = @search.result(distinct: true).group(:name).sum(:sold) 
    end 

    def create 
    @sale = Sale.find(params[:sale_id]) # Find specific branch_product we will be working with 
    @branch_history_sold = @sale.branch_history_solds.create(branch_history_sold_params) # Enable whitelisted attributes to get created 
    flash[:notice] = "New products have been Sold from branch" # flash notice will show immediately after branch_history_sold gets created 
    redirect_to branch_product_path(@branch_product) # redirect to branch_product show page 
    end 

    def destroy 
    @sale = Sale.find(params[:sale_id]) # Find specific branch_product we will be working with 
    @branch_history_sold = @sale.branch_history_solds.find(params[:id]) # Find specific branch_history_sold that will be destroyed 
    @branch_history_sold.destroy # destroy branch_history_sold 
    flash[:notice] = "Newly sold products have been added back to branch" # flash notice will show immediately after branch_history_sold is destroyed 
    redirect_to branch_product_path(@branch_product) # redirect to branch_product show page 
    end 

    private 

    def branch_history_sold_params 
    params.require(:branch_history_sold).permit(:sold, :customer_name) # whitelisted attributes 
    end 

end 

그리고 fields_for 속성

<div class="container"> 
     <div class="row"> 
      <%= form_for @sale, html: { class: "form-horizontal" } do |f| %> 
       <!-- Text input--> 
       <div class="form-group"> 
        <label class="col-md-1 control-label">R/NO</label> 
        <div class="col-md-6"> 
         <%= f.collection_select(:branch_id, Branch.all, :id, :name) %> 
        </div> 
       </div> 
       <!-- Text input--> 
       <div class="form-group"> 
        <label class="col-md-1 control-label">R/NO</label> 
        <div class="col-md-6"> 
         <%= f.text_field :receipt_no, placeholder: "Receipt number", class: "form-control input-md" %> 
        </div> 
       </div> 
       <!-- Text input--> 
       <div class="form-group"> 
        <label class="col-md-1 control-label" >Name</label> 
        <div class="col-md-6"> 
         <%= f.text_field :customer_name, placeholder: "Prince Abalogu", class: "form-control input-md" %> 
        </div> 
       </div> 
       <!-- Appended Input--> 
       <div class="form-group"> 
        <label class="col-md-1 control-label">Number</label> 
        <div class="col-md-6"> 
         <%= f.text_field :phone_number, placeholder: "08185438075", class: "form-control input-md" %> 
        </div> 
       </div> 
       <!-- Appended Input--> 
       <div class="form-group"> 
        <label class="col-md-1 control-label">E-mail</label> 
        <div class="col-md-6"> 
         <%= f.text_field :email, placeholder: "[email protected]", class: "form-control input-md" %> 
        </div> 
       </div> 

       <!-- Appended Input--> 
       <%= f.fields_for :branch_history_solds, @sale.branch_history_solds.build do |b| %> 
        <div class="form-group"> 
         <label class="col-md-1 control-label">Product</label> 
         <div class="col-md-6"> 
         <%= b.number_field :sold, placeholder: "Quantity" %> 
         </div> 
        </div> 
        <div class="form-group"> 
         <label class="col-md-1 control-label"></label> 
         <div class="col-md-6"> 
          <% @branch = BranchProduct.where :branch_id, 19 %> 
          <%= b.collection_select(:branch_product_id, BranchProduct.where(branch_id: params[:branch_id]), :id, :name) %> Select Product 
         </div> 
        </div> 
       <% end %> 

       <!-- Appended Input--> 
       <div class="form-group"> 
        <label class="col-md-1 control-label"></label> 
        <div class="col-md-6"> 
         <%= f.check_box :paid %> Paid 
        </div> 
       </div> 

       <!-- Button (Double) --> 
       <div class="form-group"> 
        <label class="col-md-1 control-label"></label> 
        <div class="col-md-8"> 
         <%= f.button :submit %> 
        </div> 
       </div> 
      <% end %> 
     </div> 
    </div> 
와 마지막으로 내 양식

양식이 표시되지만 현재 문제는 내가 제출 한 후 branch_history_solds를 작성하지 않는다는 것입니다. 그것은

답변

2

문제는 중첩 된 기록은 항상 양식 때문에 true를 돌려줍니다 거부해야하는지 여부를 평가하기 위해 사용하는 람다/모델이 content 속성이없는 것입니다 :

class Sale < ActiveRecord::Base 
    has_many :branch_history_solds 
    accepts_nested_attributes_for :branch_history_solds, :reject_if => lambda { |a| a[:content].blank? }, 
           :allow_destroy => true 
end 

또한이야을 잘못된 특성을 허용 목록에 넣으십시오 branch_history_sold 아니요 branch_history_solds. 그러나 당신의 일반적인 설정은 그냥 일반 이상하고 나는 그것의 단지 이름 알고하지 않습니다

class Sale < ActiveRecord::Base 
    has_many :branch_history_solds 
    accepts_nested_attributes_for :branch_history_solds, :reject_if => lambda { |a| a[:branch_product_id].blank? }, 
           :allow_destroy => true 
end 

을하지만 많이하지 않습니다

는 실제로 전달되는 속성을 수 있도록이 변경해야 감각. 당신이 판매 시스템 또는 주문 관리 시스템의 지점을 만들려면

당신과 같이 그것을 할 것입니다 : 당신은 단지하도록해야


class OrdersController 

    def new 
    end 


    def create 
    @order = Order.new(order_params) do 
     order.customer = current_user 
    end 
    if (@order.save) 

    else 

    end 
    end 

    private 
    def order_params 
    params.require(:order) 
      .permit(:foo, :bar, line_item_attributes: [:product_id, :quantity]) 
    end 
end 

class Order 
    belongs_to :customer 
    has_many :line_items 
    has_many :products, through: :line_items 
    accepts_nested_attributes_for :line_items, 
    allow_destroy: true, 
    reject_if: -> { |li| li[:product_id].blank? || li[:quantity].blank? } 
end 

# columns: 
# - order_id [integer, index, foreign key] 
# - product_id [integer, index, foreign key] 
# - quantity [decimal or integer] 
# - price [decimal] 
# - subtotal [decimal] 
class LineItem 
    belongs_to :order 
    belongs_to :product 
end 

class Product 
    has_many :line_items 
    has_many :orders, through: :line_items 
end 
사용자가 매우 제한된 수의 통과 params - 사용자의 가격과 같은 것을 사용하지 마십시오. 실제 가격 결정 논리는 모델 계층에서 수행되어야합니다. 또한 고객 주문 정보를 주문 모델에서 분리하지 않을 것입니다. 그렇지 않으면 모든 반복 주문이 데이터를 복제하게됩니다. 검색과 같은 추가 기능을 추가하기 전에 실제 도메인 모델을 가져 오는 데 시간을 할애 할 것입니다.

+1

인벤토리를 추적하려면 추가 모델로 수행해야합니다. 위의 방법으로 인벤토리를 구부리지 마십시오. 위치 (상점, 지점 등)를 추적하는 모델과 한 위치의 제품 재고를 추적하는 모델이 필요합니다. – max

+0

@oklas 다시 읽습니다. 화이트리스트에있는 컨트롤러에 오타가 있습니다 (모델에서는 제외). 귀하의 의견은 심지어 말이되지 않습니다. – max