2016-08-01 83 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

相关问题