Rails 从另一个模型的视图调用控制器
我有一个 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>
...
我收到错误语法错误,意外的 tIDENTIFIER,期待 ')'
并且似乎找不到任何好的替代方案。
我在这里缺少什么?
已更新
这是一个逗号。 facepalm
还有很多其他问题,但这就是导致错误的原因。
<% @posts.each do |post| %>
<tr>
<td><%= link_to "upboats", upvote_post(post) %></td>
<td><%= post.name %></td>
...
I have a post
model and an upvote
model.
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
#
Now within posts/index
I want to add an upvote for the current user and the post.
Some research pointed me to write a helperposts_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
Inside my view I want to call the helper only on clicking a link but can't seem to get link_to
working properly.
<% @posts.each do |post| %>
<tr>
<td><%= link_to "upboats" upvote_post(post) %></td>
<td><%= post.name %></td>
...
I get the error syntax error, unexpected tIDENTIFIER, expecting ')'
and can't seem to find any good alternatives.
What am I missing here?
UPDATED
It was a comma. facepalm
Plenty of other issues, but that was what led to the error.
<% @posts.each do |post| %>
<tr>
<td><%= link_to "upboats", upvote_post(post) %></td>
<td><%= post.name %></td>
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
结束开放式问题。
这是一个逗号。
更新
这是一个逗号。 facepalm
还有很多其他问题,但这就是导致错误的原因。
Closing open question.
It was a comma.
UPDATED
It was a comma. facepalm
Plenty of other issues, but that was what led to the error.