【问题标题】:Ruby on Rails: Call controller method on specific model from viewRuby on Rails:从视图中调用特定模型的控制器方法
【发布时间】:2016-09-26 20:03:52
【问题描述】:

我是 Ruby 和 Rails 的新手。 我有一个显示课程列表的视图。

<% if defined?@offerings %>
   .....
<% @offerings.each do |offering| %>
    <tr>
      <td><%=offering.semester %></td>
      <td><%=offering.location %></td>
    </tr>
  <%end %>

我需要添加一个与每个产品相关联的注册按钮。此注册按钮应调用减少特定产品容量属性的产品控制器方法。

如何将每个按钮绑定到其各自的产品?或者,如何将正确的产品作为参数传递给控制器​​方法?

【问题讨论】:

    标签: ruby ruby-on-rails-4 view model controller


    【解决方案1】:

    添加另一个&lt;td&gt;,像这样:

    <td><%= link_to "Enroll", your_method_path(offering) %></td>
    

    【讨论】:

    • 我在网上看到了这个,但我对 your_method_path(offering) 中的内容感到非常困惑?
    • 如果尚未完成,您必须在 config/routes.rb 中将路由添加到您的方法中。然后,要找到路径,您可以在终端中使用它:rake routes,它会告诉您方法的路径。
    • 你能说得更具体些吗,我对 Rails 很陌生。运行 rake 路线我得到: PUT /offerings/:id(.:format) Offerings#update.
    【解决方案2】:

    你可以使用button_to方法,默认会提交一个POST请求,像这样:

    &lt;td&gt;&lt;%= button_to "Enroll", enroll_offering_path(offering) %&gt;&lt;/td&gt;

    要让enroll_offering_path 工作,您需要:

    • PUT /offerings/:id/enroll 路由:

      # config/routes.rb`
      
      resources :offerings do
        post 'enroll', on: :member
      end
      
    • #enroll 控制器操作:

      # app/controllers/offerings_controller.rb
      
      class OfferingsController < ApplicationController
        ...
        def enroll
          # Here you would do something like...
          @offering = Offering.find(params[:id])
          @offering.decrement!(:capacity)
        end
      end
      

    您可以阅读更多关于这一切的工作原理here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2012-06-26
      • 2023-03-07
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多