I'm new on Ror... I would like to Update a Product attribute (:active from False => True) directly from my admin dashboard, using a simple link_to. When a User add a new product in my app, I (admin) check if the product respects the condition then I publish it, from my admindashboard. Here is my code:
pages/admindashboard.html.erb
Articles on waiting list: <strong><%= @notactives.count %></strong>
<% @notactives.each do |product| %>
<ul>
<li><strong><%= link_to product.name, product_path(product) %> <%= product.user.pseudo %></strong> (<%= product.updated_at.strftime("%d/%m/%Y") %>)
<% if product.active? %>
<p>publié</p>
<% elsif product.status? %>
<p>sold</p>
<% else %>
<span class="label label-success"> <%= link_to "publish the article", publish_product_path %></span>
<% end %>
</li>
</ul>
<% end %>
Pages Controller:
def publish_product
@product = Product.find(params[:id])
if @product.update(product_params)
@product.active = true
@product.save
redirect_to :admindashboard
end
end
private
def product_params
params.require(:product).permit(:name, :description, :brand, :category, :color, :size, :state, :price, :address, :status, :active)
end
routes.rb
patch '/publish_product' =>'pages#publish_product'
Thk in advance for your help
You could set the route to accept an id from the params:
patch '/publish_product/:id' =>'pages#publish_product'
Then in the link_to you use that path plus the id:
<% @notactives.each do |product| %>
...
<%= link_to 'publish the article', publish_product_path(product.id) %>
<% end %>
And in the controller you "flips" the attribute based on the current value, like:
def publish_product
@product = Product.find(params[:id])
@product.active = !@product.active
redirect_to :admindashboard if @product.save
end