[英]Put Request From Index Page In Rails
I am making a site that has a bunch of photos and under each photo is a button that says Upvote. 我正在制作一个包含一堆照片的网站,每个照片下面都有一个按钮,上面写着Upvote。 I want that button to submit a PUT request that updates a field in a database.
我希望该按钮提交一个PUT请求,以更新数据库中的字段。 I currently have this code:
我目前有以下代码:
<% @users.each do |user| %>
<%= image_tag user.avatar.url(:thumb) %>
<% form_for (@user) do |f| %>
<input name="commit" type="submit" value="Upvote">
<% end %>
<% end %>
I want it to when a user clicks the upvote button it calls the PUT request, updates the value and than redirects to the same page. 我希望它能够在用户单击upvote按钮时调用PUT请求,更新值,然后重定向到同一页面。 I cannot figure out how to do this.
我不知道该怎么做。
First your code is wrong: replace form_for(@user)
with form_for(user)
首先,您的代码是错误的:用
form_for(@user)
替换form_for(@user)
form_for(user)
Second, since the user
object already exists, it will default to PUT
. 其次,由于
user
对象已经存在,因此它将默认为PUT
。 So you've nothing to do. 因此,您无需执行任何操作。
If you want to upvote a user (not the picture?) then put this in your user_controller.rb file: 如果您要投票给用户(而不是图片?),请将其放入user_controller.rb文件中:
def upvote
@user = User.find(params[:user])
@user.upvote
end
In your app/models/user.rb 在您的app / models / user.rb中
def upvote
self.votes += 1
self.save
end
In your config/routes.rb 在你的config / routes.rb中
resources :user do
put :upvote
end
Not tested but should give you a starting point. 未经测试,但应该给您一个起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.