加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何调用另一个控制器的方法

发布时间:2020-12-17 01:50:20 所属栏目:百科 来源:网络整理
导读:我需要从另一个控制器调用方法.什么是最好的方法?例如: catalogues_controller.rb class Site::CataloguesController ApplicationController respond_to :js,:html def index produc_list # call method other controller endend other_controller.rb clas
我需要从另一个控制器调用方法.什么是最好的方法?例如:

catalogues_controller.rb

class Site::CataloguesController < ApplicationController
  respond_to :js,:html

  def index
    produc_list # call method other controller
  end
end

other_controller.rb

class OtherController < ApplicationController

  respond_to :js,:html

  def produc_list
     myObj = Catalagues.find(params[:id])
     render :json => myObj
  end
end

解决方法

您可以实现一个模块,并将其包含在Controller中.

我们称这个模块为“产品助手”:

# In your app/helpers
# create a file products_helper.rb
module ProductsHelper

  def products_list(product_id)
    catalague = Catalagues.where(id: product_id).first
    render :json => catalague
  end

end

然后,在控制器中,您需要使用此方法:

class Site::CataloguesController < ApplicationController
  include ProductsHelper

  respond_to :js,:html

  def index
    products_list(your_id) # replace your_id with the corresponding variable
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读