【问题标题】:update a product attribute with link_to in my admindashboard rails在我的 admindashboard rails 中使用 link_to 更新产品属性
【发布时间】:2018-06-22 20:05:24
【问题描述】:

我是 Ror 的新手... 我想使用简单的 link_to 直接从我的管理仪表板更新产品属性(:从 False => True 激活)。 当用户在我的应用程序中添加新产品时,我(管理员)检查产品是否符合条件,然后我从我的管理仪表板发布它。 这是我的代码:

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

页面控制器:

  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'

提前寻求您的帮助

【问题讨论】:

    标签: ruby-on-rails controller routes attributes link-to


    【解决方案1】:

    您可以设置路由以接受来自参数的 id:

    patch '/publish_product/:id' =>'pages#publish_product'
    

    然后在link_to中你使用那个路径加上id:

    <% @notactives.each do |product| %>
      ...
      <%= link_to 'publish the article', publish_product_path(product.id) %> 
    <% end %>
    

    并且在控制器中,您根据当前值“翻转”属性,例如:

    def publish_product
      @product = Product.find(params[:id])
      @product.active = !@product.active
      redirect_to :admindashboard if @product.save
    end
    

    【讨论】:

    • 谢谢塞巴斯蒂安,但这仍然不起作用......我有以下错误:页面中的 NoMethodError#admindashboard 未定义方法 `publish_product_path'
    • 这是一个路由名称错误,你可以尝试更新路由并给它一个别名吗? patch '/publish_product/:id' =&gt;'pages#publish_product', as: :publish_product
    • 现在我有一个新错误:路由错误没有路由匹配 [GET] "/publish_product/16"
    • 对不起,那是我的错,注意link_to默认创建一个GET请求,所以你必须指定要使用的HTTP动词将是PATCH,使用方法选项,如&lt;%= link_to 'publish the article', publish_product_path(product.id), method: :patch %&gt;
    • 你是对的。这样可行!谢谢@Sebastian Palma
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多