C.Yee C.Yee - 4 months ago 7
Ruby Question

Replace model data when there is same product id

Hi fellow programmers,

I am stuck in this small problem which has been bugging me for the past 2 days. In my project there is 2 modals, product and special_price. What i am trying to achieve to is replace the price for all available product if there is an entry of the product_id in the special_prices table. Hence, my model file is as below:

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


my customer controller as where the prices will be shown on the show action is as:

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


in my views

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 %>


By using the codes above, i am only able to get 1 product to show its special_price. But when i add other entry of special prices of different products_id the array would not update itself. I have done some research and i think it might have something to do with local variable and instance variable, can anyone point me to the right direction? thanks a lot! i'd appreciate any advise.

Answer

Here is my suggestion: change _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 %>

since Product has_many :special_prices you can call a product special prices by calling product.special_prices and that will return a collection of special prices for that certain product.

Comments