当存在相同的产品ID时替换模型数据

时间:2016-08-01 03:24:10

标签: ruby-on-rails ruby ruby-on-rails-4

嗨其他程序员,

我陷入了这个小问题,这个问题在过去两天一直困扰着我。在我的项目中有2个模态,product和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

我的客户控制器将在show动作中显示价格,如下所示:

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的特殊价格的其他条目时,数组不会自行更新。我做了一些研究,我认为它可能与局部变量和实例变量有关,有人能指出我正确的方向吗?非常感谢!我很感激任何建议。

1 个答案:

答案 0 :(得分: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来调用产品特价,并返回该特定产品的特价价格。