这是按钮:
<%= 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
答案 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表单,默认情况下表单是邮政类型,因此您不需要为邮政类型的路线指定方法类型帖子。