【问题标题】:Rails calling a controller from another model's viewRails 从另一个模型的视图调用控制器
【发布时间】:2011-10-16 05:39:39
【问题描述】:

我有一个post 模型和一个upvote 模型。

upvote.rb

class Upvote < ActiveRecord::Base
  has_one :user
  belongs_to :post
end
# == Schema Information
#
# Table name: upvotes
#
#  id         :integer         not null, primary key
#  user_id    :integer
#  post_id    :integer
#  comment    :text
#  created_at :datetime
#  updated_at :datetime
#

现在在posts/index 内,我想为当前用户和帖子添加一个赞成票。

一些研究让我写一个助手 posts_helper.rb

module PostsHelper
  def upvote_post(post)
    @upvote = Upvote.new
    @upvote.user_id = current_user.id
    @upvote.post_id = post.id
    if @upvote.save
     flash.now[:notice] = 'Upvote was successfully created.'
    end
  end
end

在我看来,我只想在单击链接时调用帮助程序,但似乎无法让 link_to 正常工作。

<% @posts.each do |post| %>
  <tr>
    <td><%= link_to "upboats" upvote_post(post) %></td>
    <td><%= post.name %></td>
...

我收到错误 syntax error, unexpected tIDENTIFIER, expecting ')' 并且似乎找不到任何好的替代方案。

我在这里错过了什么?


更新

这是一个逗号。 掌心

还有很多其他问题,但这就是导致错误的原因。

<% @posts.each do |post| %>
  <tr>
    <td><%= link_to "upboats", upvote_post(post) %></td>
    <td><%= post.name %></td>
...

【问题讨论】:

  • 逗号,你少了一个逗号。你的助手闻起来像控制器。
  • 回想起来应该是一个控制器。我只是在 0 睡眠。
  • 有争议的。不过绝对低于平均水平。
  • 别忘了添加答案并稍后接受,这样其他人可能会跳过你的(现在打开的)问题。

标签: ruby-on-rails-3 helper link-to


【解决方案1】:

结束未决问题。

这是一个逗号。


更新

这是一个逗号。掌心

还有很多其他问题,但这就是导致错误的原因。

<% @posts.each do |post| %>
  <tr>
    <td><%= link_to "upboats", upvote_post(post) %></td>
    <td><%= post.name %></td>
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2017-04-08
    • 1970-01-01
    • 2011-08-11
    相关资源
    最近更新 更多