【问题标题】:Rails 4: 'redirect_to current_thing' undefined errorRails 4:'redirect_to current_thing'未定义错误
【发布时间】:2015-01-11 20:07:42
【问题描述】:

我有一个模型“事物”,每个模型都有_many“评论”,每个模型又都有_many“投票”。我希望能够在 Thing 显示页面上对 cme​​ts 进行投票。这是我目前所拥有的:

评论控制器:

def votecomment
  @comment = Comment.find(params[:id])
  Vote.create!(voteable_id: params[:id], voteable_type: 'Comment')
  redirect_to current_thing
end

事物视图:

<%= link_to “Vote”, vote_comment_path(:id => comment.id), method: :post %>

路线:

post 'comments/:id/vote' => 'comments#vote', as: 'vote_comment'

但是我得到了这个错误:

NameError in CommentsController#votecomment 
undefined local variable or method `current_thing' for #<CommentsController:0x007f98efa69c00>

我尝试将方法移动到 Things 控制器,但我得到了完全相同类型的错误。

我做错了什么?

【问题讨论】:

  • 试试redirect_to @comment.thing
  • 你是怎么想到current_thing的?
  • 你能把current_thing的代码贴在你的控制器里
  • @Santosh 啊,效果很好!谢谢你。我在 current_user 工作的地方看到了一堆答案,所以我认为 current_thing 也可以工作。
  • 很高兴它成功了。我已将其添加为答案。 :)

标签: ruby-on-rails ruby redirect ruby-on-rails-4 routes


【解决方案1】:

假设你在comment.rb中有如下关系

belongs_to :thing

您可以使用@comment.thing 访问评论的事物对象。由于 redirect_to 接受对象,你可以这样做

redirect_to @comment.thing

【讨论】:

    【解决方案2】:

    如果你熟悉 devise 并且你看到 ex current_user,你必须明白没有什么叫做 current_thing,这是 gem 中的一个方法,而不是你创建的每个模型的填充方法。

    因此,如果您想要类似的添加方法到您的 application_controller 甚至应用程序助手以获取 current_thing

    def current_thing
      Thing.find() --> or whatever the way you get that current thing.
    end
    

    【讨论】:

      猜你喜欢
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      相关资源
      最近更新 更多