【问题标题】:How can i run my method by clicking on button on view?如何通过单击视图上的按钮来运行我的方法?
【发布时间】:2018-09-05 09:33:23
【问题描述】:

我有一个方法:

def add_to_favorite(id)
    current_user.update(favorite_photos: current_user.favorite_photos + " " + id)
end

此方法在字符串 current_user.fafavorite_photos 的末尾添加一些信息。

如何通过单击视图中的按钮或链接来运行此方法? 没有 JS,只使用 Ruby on Rails。 谢谢。

【问题讨论】:

  • 我在 aplication_helper.rb 中有这个方法
  • 我不认为如果您在 application_helper 中定义一个方法并希望它由buttonlink 触发它会起作用。一种方法是将其定义为控制器操作并执行。
  • 我不知道为什么,但是这种方法只适用于应用程序助手

标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5


【解决方案1】:

如果您想使用链接来调用操作。

# controller
def add_to_favorite(id)
    current_user.update(favorite_photos: current_user.favorite_photos + " " + id)
end

# routes.rb
put 'favorites/:id/add_to_favorite'

# view
<%= link_to 'Add_Favorite', add_to_favorite_path(@favorite), method: :put %>

如果你想要一个按钮来做,那么

<%= form_tag add_to_favorite_path, method: :put do %>
  <%= submit_tag 'Add_To_Favorite' %>
<% end %>

【讨论】:

  • 或者只是把link_to设置成一个按钮。
猜你喜欢
  • 2012-01-23
  • 2019-12-23
  • 2020-12-07
  • 2019-12-03
  • 2022-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
相关资源
最近更新 更多