2016-08-01 74 views
1

喜同胞程序員,時,有相同的產品編號

我被困在已被竊聽我過去的2天內對該小問題更換模型數據。在我的項目中有兩個模塊,產品和special_price。如果在special_prices表中存在product_id條目,我試圖實現的是替換所有可用產品的價格。因此,我的模型文件如下:

product.rb

class Product < ActiveRecord::Base 
    has_many :special_prices, dependent: :destroy 

    before_save :upcase_stock_code 

    validates :name, presence: true, length: { maximum: 50 } 
    validates :stock_code, presence: true, length: { maximum: 20 } 
    validates :status, presence: true, length: { maximum: 10 } 
    validates :default_price, presence: true 
end 

special_price.rb

class SpecialPrice < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :customer 

    validates :product_id, presence: true, uniqueness: { scope: [:customer_id] } 
    validates :customer_id, presence: true 
    validates :price, presence: true 
end 

我的客戶控制器,其中價格將在節目中的動作顯示是:

def show 
    @customer = Customer.find(params[:id]) 
    @customer_active = Customer.find_by(id: params[:id], status: "active") 
    @user = User.find_by(params[:user_id]) 
    @special_price = SpecialPrice.find_by(customer_id: params[:id]) 
    @special_prices = SpecialPrice.where(customer_id: params[:id]) 
    @products = Product.all 
end 

在我的意見

show.html.erb

<div class="tab-pane" id="prices"> 
    <h1>Products</h1> 
    <div> 
     <%= render 'special_prices/price' %> 
    </div> 
</div> 

_price.html.erb

<% @products.each do |k| %> 
    <span> 
    <%= k.id %> 
    <%= k.name %> 

    <% if k.id == @special_price.product_id %> 
     <%= @special_price.price %> 
    <% else %> 
     <%= k.default_price %> 
    <% end %> 
    </span></br> 
<% end %> 

通過使用上述代碼,我只能得到1個產品,以顯示其special_price。但是當我添加不同products_id的特殊價格的其他條目時,數組不會自動更新。我已經做了一些研究,我認爲它可能與局部變量和實例變量有關,任何人都可以指向正確的方向嗎?非常感謝!我會很感激任何意見。

+0

如果將新的'special_prices'添加到現有產品中,您是否成功地更新了'Product's:special_prices'? – mrvncaragay

+0

是的。它成功更新,但只有1個產品:special_prices,即使該客戶有2個或更多的special_prices。 –

回答

0

這裏是我的建議:改變_price.html.erb

<% @products.each do |k| %> 
    <span> 
    <%= k.id %> 
    <%= k.name %> 

    <!-- show product special_prices --> 
    <% if !k.special_prices.empty? %> 
     <%= k.special_prices.each do |p| %> 
     <span><%= p.price %></span> 
     <% end %> 
    <% else %> 
     <%= k.default_price %> 
    <% end %> 
    </span> 
<% end %> 

因爲產品has_many :special_prices可以通過調用product.special_prices調用一個特殊的產品價格,這將返回的特殊價格收集某些產品。

+0

Thanks !!這對我來說很好,我只是需要扭轉如果結束聲明。再次感謝您的幫助!你救了我一堆時間! –

+0

哦,是的,只是意識到應該是'除非'或!很高興它解決了你的問題 – mrvncaragay

相關問題