简体   繁体   中英

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. I want that button to submit a PUT request that updates a field in a database. 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. I cannot figure out how to do this.

First your code is wrong: replace form_for(@user) with form_for(user)

Second, since the user object already exists, it will default to 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:

def upvote
  @user = User.find(params[:user])
  @user.upvote
end

In your app/models/user.rb

def upvote
  self.votes += 1
  self.save
end

In your config/routes.rb

resources :user do
  put :upvote
end

Not tested but should give you a starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM