update database on click - ruby-on-rails

hi i am trying to update a value within my database (PostgreSQL) when a user clicks a certain link, though what i have is working, i dont think its best practice. if anyone can show how i could better achieve this would be great
view
%ul.button-group.round.even-3
%li= link_to '<i class="general foundicon-checkmark"></i>'.html_safe, accept_availability_path(a), :method => 'put', :remote => true, :class => 'button success tiny', :id => a.id, :disable_with => ''
controller
def accept
#availability = Availability.find(params[:id])
#availability.available= true
respond_to do |format|
if #availability.update_attributes(params[:availability])
format.html { render :nothing => true }
format.js
else
format.html { render :action => "edit" }
format.js
end
end
end
routes
resources :availabilities do
put 'accept', :on => :member
put 'decline', :on => :member
end

There's nothing particularly wrong with what you're doing. Your controller doesn't need to use update_attributes, you aren't passing any attributes into it. You can just save it with the change to .available
def accept
#availability = Availability.find(params[:id])
#availability.available = true
respond_to do |format|
if #availability.save
format.html { render :nothing => true }
format.js
else
format.html { render :action => "edit" }
format.js
end
end
end
You could neaten your routes like so:
resources :availabilities do
member do
put :accept
put :decline
end
end

Related

Create a new Record from link_to results in urlgenerationerror

I am trying to create a record in a table direcly when the user clicks on a link.
However it is generating the following error when it tries to load the view.
ActionController::UrlGenerationError in SopHeaders#show
No route matches {:action=>"create", :company_id=>2, :controller=>"sop_detail", :cost=>0.1e2, :cost_sop=>0.103e2, :customer_id=>1, :desc1=>"Printer cable YDP30 - Secura 224 ICEU", :flag_required=>true, :id=>"4", :list_price=>0.0, :opportunity_id=>"9", :product_code=>"01-69Y03293", :quantity=>1, :sophead_id=>4, :unit_price=>0.0}
My view
<%= link_to 'Add to Quote', {:controller => "sop_details",
:action => "create",
:sophead_id => #sop_header.id,
:customer_id => #customer.id,
:company_id => #customer.company_id,
:product_code => stock.product_code,
:unit_price => stock.price,
:quantity => 1,
:cost => stock.cost,
:cost_sop => stock.cost_sop,
:list_price => stock.list_price,
:flag_required => true,
:desc1 => stock.desc1},
:method => "post" %>
My Controller
def new
#sop_detail = SopDetail.new
end
def create
respond_to do |format|
if #sop_detail.save
format.html { redirect_to customer_opportunity_sop_header_path(#customer, #opportunity, #sop_header) }
format.json { render :show, status: :created, location: #sop_header }
else
format.html { render :new }
format.json { render json: #sop_header.errors, status: :unprocessable_entity }
end
end
end
My route table output
customer_opportunity_sop_header_sop_details GET /customers/:customer_id/opportunities/:opportunity_id/sop_headers/:sop_header_id/sop_details(.:format) sop_details#index
POST /customers/:customer_id/opportunities/:opportunity_id/sop_headers/:sop_header_id/sop_details(.:format) sop_details#create
new_customer_opportunity_sop_header_sop_detail GET /customers/:customer_id/opportunities/:opportunity_id/sop_headers/:sop_header_id/sop_details/new(.:format) sop_details#new
edit_customer_opportunity_sop_header_sop_detail GET /customers/:customer_id/opportunities/:opportunity_id/sop_headers/:sop_header_id/sop_details/:id/edit(.:format) sop_details#edit
customer_opportunity_sop_header_sop_detail GET /customers/:customer_id/opportunities/:opportunity_id/sop_headers/:sop_header_id/sop_details/:id(.:format) sop_details#show
PATCH /customers/:customer_id/opportunities/:opportunity_id/sop_headers/:sop_header_id/sop_details/:id(.:format) sop_details#update
PUT /customers/:customer_id/opportunities/:opportunity_id/sop_headers/:sop_header_id/sop_details/:id(.:format) sop_details#update
What am I doing wrong?
Your redirect_to path is not in your routes. You want to go to the customer_opportunity_sop_header_path path while this is not in your routes. I guess you want to navigate to the customer_opportunity_sop_header_sop_details_path.

Rails passing params in link_to how to make it secure

I am trying to create a like and dislike function inside rails for that I am using lin_to helper to pass params but there is an issue when ever someone tries to copy paste the links it updated the database . I am using ajax to make this function work here is the code for my method .
Controller code:
class FeedLikesController < ApplicationController
before_action :authenticate_user! ,only: [:create, :destroy]
before_action :get_feed ,only: [:create, :destroy]
def index
#fees = FeedLike.all
respond_to do |format|
format.html
format.js
end
end
def update
#feed_likes = FeedLike.find_or_create_by(feed_like_params)
respond_to do |format|
if #feed_likes.save
format.html { redirect_to root_url, notice: 'Like ' }
end
end
end
def create
#feed_like_counter = Feed.find(params[:feed_id])
#feed_likes = FeedLike.find_or_create_by(:feed_id => params[:feed_id],:user_id =>params[:user_id])
#f = #feed_like_counter.like_count
#feed_like_counter.like_count = #f+1
#feed_like_counter.save
respond_to do |format|
if #feed_likes.save
format.html { redirect_to root_url, notice: 'Like ' }
format.js
end
end
end
def delete
end
def destroy
#feed_like_counter = Feed.find(params[:feed_id])
#feed_likes = FeedLike.where(feed_like_params)
#f = #feed_like_counter.like_count
#feed_like_counter.like_count = #f-1
#feed_like_counter.save
respond_to do |format|
if #feed_likes.destroy_all
format.html { redirect_to root_url, notice: 'Unlike ' }
format.js
end
end
end
def feed_like_params
params.permit(:user_id, :feed_id)
#params[:market_place]
end
def get_feed
#feed = Feed.find(params[:feed_id])
end
end
And in views my link is like this:
<div class="feed-like-<%= #feed %> " >
<%= link_to "like",{ :action => 'create', :controller => 'feed_likes', :feed_id => #feed, :user_id => current_user.id, :remote => true }, method: :post,class: "btn btn-primary" %>
</div>
And dislike link is like this:
<div class="feed-like-<%= #feed %> " >
<%= link_to "Dislike",{ :action => 'destroy', :controller => 'feed_likes', :feed_id => #feed, :user_id => current_user.id, :remote => true }, class: "btn btn-primary" %>
</div>
And my routes is like :
get "/feed_likes/:feed_id/feed_likes/:user_id" => "feed_likes#destroy"
post "/feed_likes/:feed_id/feed_likes/:user_id" => "feed_likes#create"
Here the issue is whenever someone wants to like the feed when I passes the url direclty it updated the database how can I restrict this only when user click the button only then it update the database not by url :
There is another issue with this I am using ajax onclick event it updated the database but when I click the like button fast it update the databse 2 or 3 times before the dislike partial appear . Is there any way I can use this .
I find a solution for this question it was very easy I was trying to generate the routes not in rails way so I did some changes . First I added
resources :feed_likes
and then replace the links like this :
<%= link_to "Dislike", feed_like_path(:feed_id => #feed, :user_id => current_user.id ), :confirm => 'Are you sure?',:remote => true, :method => :delete,data: { disable_with: "Processsing..." }, class: "btn btn-primary" %>
<%= link_to "like", feed_likes_path(:feed_id => #feed, :user_id => current_user.id ), :confirm => 'Are you sure?',:remote => true, :method => :post, data: { disable_with: "Processsing..." }, class: "btn btn-primary" %>

Want to have a partial update with ajax

I have a form:
<% form_tag({:controller => "/faq", :action => 'search_ajax'}, :update => "help_results", remote: true) do %>
that is going to the search_ajax action which is supposed to update the help_results div. That action is supposed to render a partial at the end, but I for sure am having syntax issues:
def search_ajax
#categories = HelpCategory.find(:all)
if params[:query].not_blank? && params[:query] != "Search for help about..."
#query = params[:query]
#terms = params[:query].split.map {|t| "%#{t.downcase}%" }
options = {
:allow_partial_match => true,
:order => 'fulltext_match_score DESC',
}
#results = SearchableText.search_model(HelpItem, #query, options).uniq
#results = {"Search Results" => #results} if !#results.blank?
#complicated_query = HelpItem.is_complicated_query?(#query)
#search_included = true
else
#results = HelpItem.all.group_by {|item| item.category.name rescue "Misc"}
#search_included = false
end
render :partial => "results"
respond_to do |format|
format.js do
render :partial => 'results'
end
format.html do
render :partial => 'results'
end
end
end
Some of the respond_to area is commented out. I am getting the error message:
ActionController::DoubleRenderError in FaqController#search_ajax
I know that if I add the remote => true helper into my form that the controller action needs to respond to js. I'm pretty sure this is a syntax error. The respond_to also comes at the end of my controller action.
Remove the
render :partial => "results"
Above the respond_to block

rails delete a record with multiple conditions

I'm trying to use .find or .where to find a certain record in my database to delete, but I'm having trouble...
I have this in my routes
resources :objects do
delete 'item' => 'objects#item_destroy', :as => :item_destroy
end
In my controller
def item_destroy
#object = Object.find(params[:object_id])
#puser = Puser.find_by_user_id(current_user)
if #mine = Mine.where(:puser_id => #puser).where(:object_id => #object)
#mine.destroy
respond_to do |format|
format.html { redirect_to :back }
format.xml { head :ok }
end
end
end
However I'm getting this error:
wrong number of arguments (0 for 1)
My link to destroy is this:
<%= link_to "Delete me", object_item_destroy_path, method: :delete, :class => "pure-button pure-button-primary" %>
Can someone assist me?
Thanks!
EDIT::
also, when I'm only getting these parameters:
{"_method"=>"delete",
"authenticity_token"=>"fdsagfHFUWlfiwoqobGBW92&9",
"object_id"=>"21"}
I'm not getting puser_id?
Try this:
<%= link_to "Delete me", object_item_destroy_path(object_id: #object), method: :delete, :class => "pure-button pure-button-primary" %>
UPDATE:
Change you objects_controller.rb file's method:
def item_destroy
#object = Object.find(params[:object_id])
#puser = Puser.find_by_user_id(current_user)
if #mine = Mine.where(:puser_id => #puser).where(:object_id => #object).first
#mine.destroy
respond_to do |format|
format.html { redirect_to :back }
format.xml { head :ok }
end
end
end
Here, when you say: Mine.where(:puser_id => #puser).where(:object_id => #object), it will give you an ActiveRecord::Relation object, not the Mine's object, and hence destroy method is not available the way you're trying to invoke it.
I also encourage you to use associations here. Like:
#puser.mines.where(:object_id => #object).first
# or
#puser.mines.find_by_object_id(#object)
<%= link_to "Delete me", object_item_destroy_path**(:id => "something" or the object you want to delete)**, method: :delete, :class => "pure-button pure-button-primary" %>
Yup, no id is being passed in because no id is being put into the link.

Rails how can I pass collection to a partial view, that is rendered from *.js.erb file

When I do this in my update.js.erb from the RewardsController:
$('div#rewards_list').html("<%=
escape_javascript(render :partial => 'shared/rewards',
:collection => #rewards,
:as => reward,
:locals => { :user => #user }
)
%>");
But the log says:
ActionView::Template::Error (undefined local variable or method `reward' for
#<#<Class:0xbb395d8>:0xbb3774c>):
In my 'update' action method:
def update
#user = User.find(params[:user_id])
#reward = #user.rewards.find(params[:id])
respond_to do |format|
if #reward.update_attributes(params[:reward])
#rewards = #user.rewards
format.html { redirect_to #user }
format.js
else
flash[:error] = "There is an error while updating the reward, please try again!"
format.html { redirect_to #user }
end
end
end
The :as option should be given a symbol, not a variable (and especially not a variable that doesn't exist), perhaps you mean this:
$('div#rewards_list').html("<%= escape_javascript(render :partial => 'shared/rewards', :collection => #rewards, :as => :reward, :locals => {:user => #user}) %>");
I just changed :as => reward to :as => :reward. See the Layouts and Rendering in Rails guide for details.

Resources