创建一个按钮来更新ruby中的数据库条目

问题描述 投票:0回答:1

我用投票字段创建了一个想法数据库。我希望用户能够按一个按钮来增加一个想法的投票数,然后刷新屏幕。我创建了一个名为increment_vote的方法,但似乎无法找到如何在我的数据库中保存新的投票值。这是我的index.html.erb代码的一部分:

<% @ideas.each do |idea| %>
  <tr>
    <td><%= idea.content %></td>
    <td><%= increment_vote(idea) %></td>
    <td><%= link_to 'Vote', ideas_path(:mode => "Vote"), :class => "button", :method => :get %></td>                                      
  </tr>

如果我从投票代码的链接调用增量投票方法,我得到一个“undefined method `to_model' for true:TrueClass. Did you mean to_yaml”错误。

这是我在ideas.controller中的方法代码:

helper_method :increment_vote
  def increment_vote(idea)
    idea.votes +=1
    idea.save
   end

这目前导致错误,但它增加了表中第一个想法的投票。

有人可以帮忙吗?

ruby-on-rails
1个回答
0
投票

你不能从视图中调用increment_vote方法,你需要为它创建控制器动作并在用户点击链接时调用它

# views/ideas/index.html.erb
<% @ideas.each do |idea| %>
  <tr>
    <td><%= idea.content %></td>
    <td><%= link_to 'Vote', upvote_idea_path(idea), class: "button", method: :post %></td>                                      
  </tr>
<% end %>

# routes.rb
resources :ideas do
  post :upvote, on: :member
end

# ideas_controller.rb
def upvote
  Idea.find(params[:id]).upvote
  redirect_to :index
end

# models/idea.rb
def upvote
  update(votes: votes + 1)
end
© www.soinside.com 2019 - 2024. All rights reserved.