Rails dynamic increasing button - ruby-on-rails

I have to do an increasing value button "bg" for p1 entry in table game but it is not working... It save the game with p1 = 0 but the link_to has no effect..
Many thanks for any help!!! (And sorry for my bad English...)
controller
def create
#game = Game.new(params[:game])
#game.p1 = 0
respond_to do |format|
if #game.save
format.html { render action: "show" }
end
end
end
def show
#game = Game.find(params[:id])
respond_to do |format|
format.js {render 'hnew'}
end
end
def add_three_points
#game = Game.find(params[:id])
#game.update_attribute(:p1, #game.p1 + 3)
end
views
show.html.erb
<%= render 'hnew' %>
hnew.js.erb
$('#ajax_hidden').html("<%= escape_javascript(render('hnew')) %>");
_hnew.html.erb
<%= link_to "bg", add_three_points_path(#game.id), {remote: true, method: :put},
class: 'btn btn-small' %>
<%= #game.p1 %>
error message:
Started PUT "/add_three_points.14" for 127.0.0.1 at 2013-07-10 21:27:01 +0200
Processing by GamesController#add_three_points as
Completed 404 Not Found in 1ms
ActiveRecord::RecordNotFound (Couldn't find Game without an ID):
app/controllers/games_controller.rb:86:in `add_three_points'

The :method option of link_to is for the HTTP verb (:get, :post, :put or :delete)
What you want to do is below (using the :put method, preferred verb for updates)
<%= link_to "bg", add_three_points_path(#game), {remote: true, method: :put}, class: 'btn btn-small' %>
and in routes.rb:
put 'add_three_points' => 'games#add_three_points', :as => :add_three_points

Related

Rails acts_as_votable using AJAX to stop page reloads

I'm trying to be able to upvote using acts_as_votable without the page reloading but I'm not sure how to change the routes to make it work
Controller
def upvote
#video = Video.find(params[:id])
#ip = request.remote_ip
# Ipaddresstracker.delete_all
if Ipaddresstracker.find_by(ipaddress: #ip)
else
Ipaddresstracker.create(:ipaddress => #ip, :upvoted => true, :upvotedcount => 1)
#video.vote_by voter: User.first, :duplicate => true
end
# redirect_to :back
respond_to do |format|
format.html { redirect_to :back }
format.js { render layout: false }
end
end
View
<%= link_to like_video_path(x), method: :get, remote: true, class: "btn btn-default btn-sm" do %>
Route
resources :videos do
member do
put "like", to: "videos#upvote"
put "dislike", to: "videos#downvote"
end
end
Error
ActionController::RoutingError (No route matches [GET] "/videos/53/like"):
The route expects a put request. Change the :method option to :put
<%= link_to like_video_path(x), method: :put, remote: true, class: "btn btn-default btn-sm" do %>
Actually, if you had Jquery you can solve this problem by Jquery.
If not, try to change this format.js { render layout: false }. You need to render nothing so you can set render :nothing => true in your format.js block

Using Ajax requests in rails

Hi I want to build an app using Ajax. Whenever a user visits an other user page he can add him as a friend by clicking add friend link. This is my current code in users/show page
<% if current_user.friend?(current_user,#user) %>
<%= link_to "Unfriend", relation_path(#relation), user: #user, method: :delete, data: { confirm: 'Are you sure? This action cannot be undone' }, class: 'btn btn-default' %>
<% elsif #user != current_user %>
<%= link_to "Add Friend", friendships_path(:friend_id => user), :method => :post, class: 'btn btn-default' %>
<% end %>
My code in relations controller
def create
if params[:friend_id]
if Relation.where(user_id: current_user.id, friend_id: params[:friend_id]).present?
redirect_to user_path(params[:friend_id]), notice: "Already friends"
elsif current_user.id == params[:friend_id]
redirect_to user_path(params[:friend_id]), alert: "Invalid Request"
else
#relation = current_user.relations.new(friend_id: params[:friend_id], subject: Constants::Subject::MAKE)
if #relation.save
friend = User.find(params[:friend_id])
friend.relations.create!(friend_id: current_user.id, subject: Constants::Subject::MAKE)
redirect_to user_path(params[:friend_id]), notice: "Added as friend"
else
redirect_to user_path(params[:friend_id]), alert: "Could not add as friend"
end
end
else
redirect_to current_user, notice: "Invalid Request"
end
end
I am following this Ryan Bates rails casts. How can I make the link_to add friend Ajax request instead of html request. The current code is working fine. I want to add Ajax functionality for this. I have seen a lot of questions but I could not understand what exactly to be done. Please help.
Add remote: true to the link_to tag. There is more information in the guides abou rails and ajax. You will need a respond_to block to handle the response.
Start with adding remote: true and use the console to see the call being made and what the response is. Then you can figure out how to handle the response.
<%= link_to "Add Friend", friendships_path(:friend_id => user), :method => :post, remote: true, class: 'btn btn-default' %>
Please take a look:
Move your buttons into a partial
Render it inside a div with ID = "actions"
Update your controller response with format js
Add field create.js.erb which render your buttons by javascript
Render your flashes box by javascript by the same way (if needed)
your view_file.erb
<div id="actions">
<%= render "views/realtions/actions", relation: #relation, friend: #user %>
</div>
views/realtions/_actions.html.erb
<% if current_user.friend?(current_user, friend) %>
<%= link_to "Unfriend", relation_path(relation), user: friend, method: :delete, remote: true, data: { confirm: 'Are you sure? This action cannot be undone' }, class: 'btn btn-default' %>
<% elsif friend != current_user %>
<%= link_to "Add Friend", friendships_path(friend_id: friend.id), method: :post, remote: true, class: 'btn btn-default' %>
<% end %>
views/realtions/create.js.erb
<%- if #friend.present? %>
$("#actions").html("<%= j render 'views/realtions/actions', relation: #relation, friend: #friend %>")
<%- end %>
// render your flashes to DOM here!
controllers/relations_controller.rb
def create
if params[:friend_id]
#friend = User.find(params[:friend_id])
if Relation.where(user_id: current_user.id, friend_id: #friend.id).present?
flash[:notice] = "Already friends"
elsif current_user.id == params[:friend_id]
flash[:error] = "Invalid Request"
else
#relation = current_user.relations.new(friend_id: params[:friend_id], subject: Constants::Subject::MAKE)
if #relation.save
#friend.relations.create!(friend_id: current_user.id, subject: Constants::Subject::MAKE)
flash[:notice] = "Added as friend"
else
flash[:error] = "Could not add as friend"
end
end
else
flash[:notice] = "Invalid Request"
end
respond_to do |format|
format.js
end
end
Hope this help

Delete method in ROR route error when using remote true

I'm trying to delete post with the remote: true command in rails. Everything is working fine when i'm not using ajax. But when i use the remote true command i get an routing error.
view:
<% #posts.each do |post| %>
<%= post.title %>
<%= link_to 'delete', post_path(post), method: :delete, data: { confirm: 'Are you sure?' }, remote: true %>
<% end %>
controller:
def index
#posts = Post.all
end
def destroy
#post = Post.find(params[:id])
#post.destroy
redirect_to :back
end
routes:
resources :posts
This is the error i get in the log.
Started DELETE "/posts" for 127.0.0.1 at 2014-10-11 12:46:33 +0200
ActionController::RoutingError (No route matches [DELETE] "/posts"):
Thanks in advance.
Update. I get this when i write rake routes.
DELETE /posts/:id(.:format) posts#destroy
To get this to working.
Change:
def destroy
#posts = Post.find(params[:id])
#posts.destroy
redirect_to :back
end
To this:
def destroy
#posts = Post.find(params[:id])
#posts.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.js { head :no_content }
end
end
and:
<%= link_to 'delete', post_path(post), method: :delete, data: { confirm: 'Are you sure?' }, remote: true %>
to:
<%= link_to 'delete', post, method: :delete, data: { confirm: 'Are you sure?' }, remote: true %>
Incase anyone is having any problems with this, I managed to solve it by adding :data => { :type => :json } to the link.
For example:
<%= link_to "Delete this post", #post, :method => :delete, :remote => true, :data => { :type => :json } %>
I imagine UJS is expecting HTML, however JSON is returned so it fails and posts again (I noticed two requests).
Hope this helps!

Ruby on Rails Page not reloading on submit button click

I have an Approve button that changes status attribute of the Shop table record. When I click on it, it does change attribute, but it doesn't reload the page, so I have to reload page manually to see the result, which is very inconvenient. Looks like everything has to work, but page still not reloading.
My view has:
<%= form_for([:admin, #shop], remote: true, data: { confirm: "You sure?" }) do |fr| %>
<%= fr.hidden_field :status, :value => 2 %>
<%= fr.submit "Reject", class: "btn btn-large btn-danger" %>
<% end %>
And the controller:
def update
#shop = Shop.find(params[:id])
if #shop.update_attributes(shop_params)
flash[:success] = "Shop updated"
redirect_to([:admin, #shop])
else
render 'edit'
end
end
I would be grateful for any help, thank you!
You are using remote: true in form_for, which is making your form submission via AJAX.
You may need to add method: :put so that form hits action update instead of create.
So just try removing remote: true and add method: :put as follow and try submitting form again.
<%= form_for([:admin, #shop], method: :put, data: { confirm: "You sure?" }) do |fr| %>
<%= fr.hidden_field :status, :value => 2 %>
<%= fr.submit "Reject", class: "btn btn-large btn-danger" %>
<% end %>
maybe you are missing the respond_to do |format| calls or did you omitted them on the question?
should be like that:
def update
#shop = Shop.find(params[:id])
respond_to do |format|
if #shop.update(shop_params)
format.html { redirect_to [:admin, #shop], notice: "Shop updated"
else
format.html { render action: 'edit' }
end
end
end
hope that helps.

Rails: AJAX + destroy action in controller not working?

Hi I am currently making an app with users, albums, and photos. I managed to make the AJAX work for the create action when I upload pics, but I can't get AJAX to work for the delete. Instead, it redirects me to an empty show page for the pic. Can anyone give me some guidance?
photos controller:
def destroy
#user = User.find(params[:user_id])
#album = #user.albums.find(params[:album_id])
#photo = #album.photos.find(params[:id])
# #photo.destroy
flash[:success] = "Photo successfully deleted."
respond_to do |format|
if #photo.destroy
format.js
# format.json { render json: #photo, status: :created, location: #photo}
# redirect_to user_album_path(#user, #album)
end
end
end
destroy.js.erb (I'm supposed to have this right?)
$('.destroypicswrapper').remove(".<%= #photo.avatar.url %>");
_photodestroy.html.erb partial:
<div class="picthumb <%= photo.avatar.url %>">
<%= link_to image_tag(photo.avatar.url ? photo.avatar.url(:small) : #album.name), root_url %>
<br>
<%= link_to "Delete", user_album_photo_path(#user, #album, photo), :remote => true, method: :delete, data: { confirm: "Are you sure? "} %>
</div>
and finally the albums/edit.html.erb page where the delete is initially happening:
<% provide(:title, "Edit album") %>
<%= render 'form' %>
<div class="destroypicswrapper">
<% if #album.photos.any? %>
<%= render :partial => 'photodestroy', :collection => #album.photos, :as => :photo %>
<% end %>
</div>
I don't think you want to render the full url of an image as a class of a div. Also, your Jquery is wrong. Try something like this:
destroy.js.erb
$('.destroypicswrapper > #photo_<%= #photo.id %>').remove();
Adjust your _photodestroy.html.erb to:
<div class="picthumb" id="photo_<%= photo.id %>">

Resources