I’m new in Ruby on Rails, what I’m doing is a grocery shop website. The company have many outlets and products.
An admin can add a product and outlet, there can be different products and outlets, each outlet can have the same product but not the same price (Example outlet A and B have fish but A is $5 but B is $6)
The Admin can select and choose to assign an item to an outlet and edit the price, the final result will be stored in the OutletProduct
table.
Below is what I have done but it doesn't work and shows an error.
Product Controller Code:
def outlet
@outlet = Outlet.find(params[:id])
end
def add
@product = Product.find(params[:id])
@outlet = Outlet.find(params[:outlet_id])
end
def update
@product = Product.find(params[:id])
@outlet = Outlet.find(params[:outlet][:name])
if @product.update(product_params)
flash[:success] = "Product updated"
redirect_to @product
else
render 'add'
end
end
show.html.erb
<% provide(:title, @product.name)%>
<%= render @product %>
<div >
<aside >
<section >
<%= render 'shared/stats' %>
</section>
<div>
<%= link_to "Add to Outlet", add_path %> |
<%= link_to "Back to products", products_path %>
</div>
</aside>
</div>
add.html.erb
<h1>Add to outlet</h1>
<div >
<div >
<%= form_with(model: @product, local: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :quantity %>
<%= f.number_field :quantity, class: 'form-control' %>
<%= f.label :price %>
<%= f.number_field :price, class: 'form-control' %>
<%= f.label :outlet %>
<%= f.select :outlet, options_for_select(@outlets), :include_blank => true %>
<%= f.hidden_field :category_id, value: 1 %>
<%= f.submit "Save changes", class: "btn btn-primary" %>
<% end %>
</div>
</div>
Product Migration Table Code:
class CreateProducts < ActiveRecord::Migration[7.0]
def change
create_table :products do |t|
t.string :name
t.integer :quantity
t.integer :price
t.integer :category_id
t.timestamps
end
end
end
After add-outlet clicked (in console)
The page after clicked Add Outlet
UPDATE
Error shown in website after made changes
CodePudding user response:
In the ProductsController for action add
, it is erroring out because params[:id]
and params[:outlet_id]
are nil.
In show.html.erb <%= link_to "Add to Outlet", add_path %>
it is linking to add_path but does not specify what the value of id
or outlet_id
should be.
Try changing it to add_path(@product)
or add_path(id: @product.id)
For outlet_id
, it looks like this may not be needed, instead you may want to change the add action to return a list of outlets:
def add
@product = Product.find(params[:id])
@outlets = Outlet.all
end
UPDATE
The new error is telling you that the outlet object
does not have a method called outlet
. This is caused by: Outlet.all.collect { |l| [l.outlet, l.id] }
. You can use l.name
instead of l.outlet
.