Rails - 如何编写一个 link 来调用控制器中带有参数的动作?

Rails -- How to write a link which will be called to call a action with a parameter in controller ?

例如,在我的控制器中:

class GymController < ApplicatoinController
  def store(page)
     ...
  end
end

现在,我想通过 gym.html.slim 中的 link 调用此操作:

- a ...

但是link格式怎么调用,route.rb文件怎么写?

答案取决于您的商店页面是属于单个 Gym object 还是属于其中的 collection:

单人object

# app/controllers/gym_controller.rb
class GymController < ApplicatoinController
  before_action :fetch_gym

  def store
    # ...
  end

  private

  def fetch_gym
    @gym = Gym.find(params.require(:id))
  end
end

# config/routes.rb
resources :gyms, only: [] do
  get :store, on: :member
end

# gym.html.slim
= link_to 'Store', store_gym_path(@gym)

一个collection

# app/controllers/gym_controller.rb
class GymController < ApplicatoinController
  def store
    # ...
  end
end

# config/routes.rb
resources :gyms, only: [] do
  get :store, on: :collection
end

# gym.html.slim
= link_to 'Store', store_gym_path

在此处阅读有关 link_to and routing 的更多信息。