使用button_to将数据发送到控制器

时间:2018-02-22 01:06:29

标签: ruby-on-rails

这是按钮:

<%= button_to "I want to understand this.", articles_want_to_understand_path, :id => @article.id, method: :post %>

这是控制器代码:

def want_to_understand
  @article.user_who_wants_to_understand << current_user
  redirect_to action: :show
end

private

def set_article
  @article = Article.find(params[:id])
end

这是错误:

undefined method `user_who_wants_to_understand' for nil:NilClass

1 个答案:

答案 0 :(得分:0)

控制器中的

: -

before_action :set_article, only: [:want_to_understand]
def want_to_understand
  @article.user_who_wants_to_understand << current_user
  redirect_to action: :show
end

private

def set_article
  @article = Article.find(params[:id])
end

并在您的视图页面中: -

<%= button_to "I want to understand this.", articles_want_to_understand_path(id: @article.id) %>

附注:使用按钮转换为html表单,默认情况下表单是邮政类型,因此您不需要为邮政类型的路线指定方法类型帖子。