I have been following the Railscast raffler tutorial and am trying to create a new view in my users controller which will use Angular to display a list of all users with the role of "user" from the user table (I haven't implemented this yet), and then randomly select one of them to become winner (a winner field will be boolean checked to true). At the moment, I have decided to add a new method in the users controller, "raffle", and of course a corresponding view to show this. However, when I open users/raffle, I get the following error, and I seem to have followed the proper way of defining a route before resources:
No route matches [GET] "/raffle"
(Perhaps there are more optimal ways to do this, but my request is that I please use angular to achieve this because I really need to learn it.)
Here is my routes.rb:
Rails.application.routes.draw do
resources :scholarships
devise_for :users, :controllers => { registrations: 'registrations' }
get 'users/raffle' => 'users#raffle'
resources :users
get 'static_pages/instructions'
get 'static_pages/about'
get 'static_pages/contact'
get 'static_pages/landing_page'
root 'static_pages#landing_page'
end
Here is my users controller:
class UsersController < ApplicationController
include Devise::Controllers::Helpers
before_action :authenticate_user!
#Users who are not signed in cannot view users list
before_action :set_user, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
respond_to :html, :json, only: [:raffle]
# GET /users
# GET /users.json
def index
#users = User.all
end
def raffle
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
#user = User.new
end
# GET /users/1/edit
def edit
#user = current_user
end
# POST /users
# POST /users.json
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: #user }
else
format.html { render :new }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
#Never trust paramaters from the scary internet, man.
def user_params
params.require(:user).permit(:first_name, :last_name, :email)
end
end
My javascript file with angular:
var rafflerApp = angular.module('rafflerApp', ["ngResource"]);
rafflerApp.controller('rafflerController', function($scope, $resource) {
User = $resource("/users/:id", {id: "#id"},{update: {method: "PUT"}})
$scope.users = User.query()
//Draw a New Winner
$scope.drawWinner = function(){
pool=[];
angular.forEach($scope.users,function(user){
if(!user.winner){
pool.push(user) ;
}
});
if(pool.length >0) {
user = pool[Math.floor(Math.random()*pool.length)];
user.winner = true;
user.$update();
$scope.lastWinner = user;
}
}
});
My raffle.html.erb file:
<% if user_signed_in? && current_user.role == "Admin" %>
<h1 class="center">Winner Raffler</h1>
<h4 class="center">To select a winner for this year's scholarship, simply click "choose winner" below</h4>
<div ng-controller="rafflerController">
<ul>
<li ng-repeat="user in users">
{{user.first_name}}
<span ng-show="user.winner">Winner</span>
</li>
</ul>
</div>
<button ng-click="drawWinner()">Draw Winner</button>
<% end %>
Users schema:
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.integer "role", default: 1
t.boolean "winner", default: false
t.integer "scholarship_id"
end
Thank you in advance.
Modify your routes.rb as follow:
Rails.application.routes.draw do
# ...
# get 'users/raffle' => 'users#raffle' <-- remove this line
resources :users do
get :raffle, on: :collection
end
#...
end
Related
I have problem with my HTML sortable update in rails 6. I drag and drop some portfolio images through web page and that is working good but when i want to update the web page with updated position i got NoMethodError (undefined method `each' for nil:NilClass):
I use this script for HTML Sortable
https://github.com/jordanhudgens/devcamp-portfolio/blob/master/app/assets/javascripts/html.sortable.js
portfolio_controller:
class PortfoliosController < ApplicationController
before_action :set_portfolio_item, only: [:edit, :show,:update, :destroy]
layout "portfolio"
access all: [:show, :index, :angular], user: {except: [:destroy, :new, :create, :update, :edit]}, site_admin: :all
def index
#portfolio_items = Portfolio.by_position
end
def sort
params[:order].each do |key, value|
Portfolio.find(value[:id]).update(position: value[:position])
end
head :ok
end
def angular
#angular_portfolio_items = Portfolio.angular
end
def new
#portfolio_item = Portfolio.new
3.times { #portfolio_item.technologies.build }
end
def create
#portfolio_item = Portfolio.new(portfolio_params)
respond_to do |format|
if #portfolio_item.save
format.html { redirect_to portfolios_path, notice: 'Your Portfolio item is now live.' }
else
format.html { render :new }
end
end
end
def edit
end
def update
respond_to do |format|
if #portfolio_item.update(portfolio_params)
format.html { redirect_to portfolios_path, notice: 'The Record successfully updated.' }
else
format.html { render :edit }
end
end
end
def show
end
def destroy
#Destroy/delete the record
#portfolio_item.destroy
#Redirect
respond_to do |format|
format.html { redirect_to portfolios_url, notice: 'Record was removed' }
end
end
private
def set_portfolio_item
#portfolio_item = Portfolio.find(params[:id])
end
def portfolio_params
params.require(:portfolio).permit(:title,
:subtitle,
:body,
technologies_attributes: [:name]
)
end
end
routes.rb:
Rails.application.routes.draw do
devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register'}
resources :portfolios, except: [:show] do
put :sort, on: :collection
end
get 'angular-items', to: 'portfolios#angular'
get 'portfolio/:id', to: 'portfolios#show', as: 'portfolio_show'
get 'about-me', to: 'pages#about'
get 'contact', to: 'pages#contact'
resources :blogs do
member do
get :toggle_status
end
end
root to: 'pages#home'
end
Here is my portfolio.js :
var ready, set_position;
ready = void 0;
set_position = void 0;
set_position = function() {
$(".card").each(function(i) {
$(this).attr('data-pos', i + 1);
});
};
ready = function() {
set_position();
$('#sortable').sortable();
$('#sortable').sortable().bind('sortupdate', function(e, ui) {
var updated_order;
updated_order = [];
set_position();
$(".card").each(function(i) {
updated_order.push;
({
id: $(this).data('id'),
position: i + 1
});
});
$.ajax({
type: 'PUT',
url: '/portfolios/sort',
data: {
order: updated_order
}
});
});
};
$(document).ready(ready);
_portfolio_item.html.erb :
<div class="card" data-id="<%= portfolio_item.id %>">
<%= image_tag portfolio_item.thumb_image unless portfolio_item.thumb_image.nil? %>
<p class="card-text">
<span>
<%= link_to portfolio_item.title, portfolio_show_path(portfolio_item) %>
</span>
<%= portfolio_item.subtitle %>
</p>
</div>
Thank you for your helps!
The only place I see an each statement is in the sort method of your PortfoliosController.
params[:order].each
You need to set your params[:order] or prevent this error from happening by checking if it is set. You could use the save navigation operator:
params[:order]&.each
Or you could check if the order parameter is set with the present? method.
if params[:order].present?
params[:order]&.each
I'm currently trying to use the nested form with cocoon, is awesome !! But I'm facing to an interrogation and I don't know which way I should take.
Relations :
Ranch have Cows
Ranch have Productions
Production have nested form Iproductions
What I'm trying to do now is implement my iteration |c| into each of my iproductions:cow_id elements
My code:
(My_form production)=
<%- #cows.each do |c| %>
<div class="row">
<div class="col-md-12">
<div id="Order">
<%= f.simple_fields_for :iproductions do |ip| %>
<%= render 'iproductions_fields', f: ip, cow: c %>
<%end%>
<div class="Order_links">
<%= link_to_add_association c.name, f, :iproductions, cow: c, class: "btn btn-default" %>
</div>
</div>
</div>
</div>
(My iproductions_fields)=
<div class="form-inline clearfix">
<div class="nested-fields">
<%= f.input :cow_id, :input_html => { :cow_id => :cow } %>
<%= f.input :quantity, input_html: {class: "form-input form-control"} %>
<%= link_to_remove_association "Supprimer", f, class: "form-button btn btn-default" %>
</div>
</div>
(My productions_controllers)=
class ProductionsController < ApplicationController
before_action :authenticate_user!
skip_before_action :configure_sign_up_params
before_action :set_ranch
before_action :set_production, except: [:create, :new, :show]
before_action :set_production2, only: [:show]
# GET /productions
# GET /productions.json
def index
#productions = Production.all
end
# GET /productions/1
# GET /productions/1.json
def show
#iproductions = Iproduction.where(id: params[:production_id])
end
# GET /productions/new
def new
#production = #ranch.productions.build
#cows = #ranch.cows
end
# GET /productions/1/edit
def edit
#cows = #ranch.cows
end
# POST /productions
# POST /productions.json
def create
#production = #ranch.productions.create(production_params)
#production.update(date: Date.today)
#cows = #ranch.cows
respond_to do |format|
if #production.save
format.html { redirect_to ranch_production_path(#production.ranch_id, #production), notice: 'Production was successfully created.' }
format.json { render :show, status: :created, location: #production }
else
format.html { render :new }
format.json { render json: #production.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /productions/1
# PATCH/PUT /productions/1.json
def update
respond_to do |format|
if #production.update(production_params)
format.html { redirect_to ranch_production_path(#production.ranch_id, #production), notice: 'Production was successfully updated.' }
format.json { render :show, status: :ok, location: #production }
else
format.html { render :edit }
format.json { render json: #production.errors, status: :unprocessable_entity }
end
end
end
# DELETE /productions/1
# DELETE /productions/1.json
def destroy
#production.destroy
respond_to do |format|
format.html { redirect_to ranch_productions_path(#production.ranch_id), notice: 'Production was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_ranch
#ranch = Ranch.find(params[:ranch_id])
end
def set_production2
#production = Production.find_by(id: params[:id])
end
def set_production
#production = #ranch.productions.find_by(id: params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def production_params
params.require(:production).permit(:name, :ranch_id, :created_at, :date, iproductions_attributes: [:id, :date, :cow_id, :quantity, :_destroy])
end
end
My real view , so I would like to Assign each iproduction with the button which generate the iproductions_fields
So if you have any idea of which way I can try to achieve this goal, you're welcome,
Thanks in advance
I am trying to use cocoon gem to build nested forms.
I have models for Organisation, Package::Bip and Tenor.
The associations are:
Organisation
has_many :bips, as: :ipable, class_name: Package::Bip
accepts_nested_attributes_for :bips, reject_if: :all_blank, allow_destroy: true
Package::Bip (polymorphic)
belongs_to :ipable, :polymorphic => true, optional: true, inverse_of: :bip
has_one :tenor, as: :tenor
accepts_nested_attributes_for :tenor, reject_if: :all_blank, allow_destroy: true
Tenor (polymorphic)
belongs_to :tenorable, :polymorphic => true, optional: true
The forms have:
In my organisations/_form.html.erb, I have:
<%= f.simple_fields_for :bips do |f| %>
<%= f.error_notification %>
<%= render 'package/bips/bip_fields', f: f %>
<% end %>
<%= link_to_add_association 'Add another intellectual property resource', f, :bips, partial: 'package/bips/bip_fields' %>
In my bip_fields.html.erb nested form, I have:
<%# if #package_bips.tenor.blank? %>
<%= link_to_add_association 'Add timing', f, :tenor, partial: 'tenors/tenor_fields' %>
<%# end %>
<%= f.simple_fields_for :tenor do |tenor_form| %>
<%= f.error_notification %>
<%= render 'tenors/tenor_fields', f: tenor_form %>
<% end %>
Javascript
The cocoon docs suggest adding a js file to specify association-insertion-node as a function. In my tenor_subform.js I have:
$(document).ready(function() {
$(".add_tenor a").
data("association-insertion-method", 'append').
data("association-insertion-node", function(link){
return link.closest('.row').next('.row').find('.tenor_form')
});
});
Controllers
In my organisation controller, I have:
def new
#organisation = Organisation.new
#organisation.bips
end
Note: I'm not sure if I need to add another line to my new action to create the organisation.bip.tenor instance. I'm also unsure if im supposed to add has_one through association on the organisation.rb that references the tenor.
def organisation_params
params.fetch(:organisation, {}).permit(:title, :comment,
bips_attributes: [:id, :status, :_destroy,
tenor_attributes: [:id,:commencement, :expiry, :_destroy]
],
In my tenor controller, I have:
def tenor_params
params.require(:tenor).permit( :commencement, :expiry)
end
ERRORS
I am not sure if I need to add tenor actions to the organisation controller (the ultimate parent of bip which in turn is the parent of tenor).
When I save all of this and try it, I get an error that says:
unknown attribute 'tenor_id' for Tenor.
When I see other SO posts with this error, its often because the :id attribute hasn't been whitelisted in the parent class. I have done that.
Can anyone see what I've done wrong?
Tenor controller
class TenorsController < ApplicationController
before_action :set_tenor, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# after_action :verify_authorized
def index
#tenors = Tenor.all
# authorize #tenors
end
def show
end
def new
#tenor = Tenor.new
# authorize #tenor
end
def edit
end
def create
#tenor = Tenor.new(tenor_params)
# authorize #tenor
respond_to do |format|
if #tenor.save
format.html { redirect_to #tenor }
format.json { render :show, status: :created, location: #tenor }
else
format.html { render :new }
format.json { render json: #tenor.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #tenor.update(tenor_params)
format.html { redirect_to #tenor }
format.json { render :show, status: :ok, location: #tenor }
else
format.html { render :edit }
format.json { render json: #tenor.errors, status: :unprocessable_entity }
end
end
end
def destroy
#tenor.destroy
respond_to do |format|
format.html { redirect_to action: :index }
format.json { head :no_content }
end
end
private
def set_tenor
#tenor = Tenor.find(params[:id])
# authorize #tenor
end
def tenor_params
params.require(:tenor).permit(:express_interest, :commencement, :expiry, :enduring, :repeat, :frequency)
end
end
You has_one relation is wrongly declared. Because you say as: :tenor makes it look for a tenor_id.
You have to declare it as follows:
has_one :tenor, as: :tenorable
Your model does not see the id of nested_attr.Add :inverse_of => #{model}.
Example:
class Tenor < ActiveRecord::Base
has_many :traps, :inverse_of => :bips
end
For more information look this or this documentation.
I'm new in rails and I'm trying to build a web app, but I encounter the limits of my abilities.
I have a classic app with user who have posts, and to put this post in public, I create a model and a controller Online.
That I'm trying to do now, It's to change the boolean :push(from Online) in false if a new Online is created with the same post_id as before.
So if I push again my post 2, the previews Online associated with the post 2 will update their :push in false.
Well, if you have any ideas about that, let me know !
Thanks
My code =
Controllers:
Onlines :
class OnlinesController < ApplicationController
before_action :authenticate_user!
before_action :set_post
before_action :owned_online, only: [:new, :edit, :update]
before_action :set_online
def new
#online = current_user.onlines.build
#online.post_id = #post.id
#online.user_id = current_user.id
end
def create
#online.user_id = current_user.id
#online.post_id = #post.id
if Online.where(post_id: params[:post_id]).any?
#online = Online.where(post_id: params[:post_id]).last.update_attributes(push: false)
end
#online = #post.onlines.create(online_params)
if #online.save
if #online.portion <= 0
#online.update(push: false)
flash[:success] = 'Veuillez indiquer le nombre de parts disponibles '
redirect_to root_path
else
#online.update(pushed_at: Time.zone.now)
#online.update(push: true)
flash[:success] = 'Votre post est en ligne !'
redirect_to root_path
end
else
render 'new'
end
end
def show
end
def update
if #onlines.update(online_params)
if #online.push == false
if #online.portion <= 1
#online.update(push: false)
flash[:success] = 'Veuillez indiquer le nombre de parts disponibles '
redirect_to root_path
else
#online.update(push: true)
flash[:success] = 'Votre post a bien été pushé !'
redirect_to root_path
end
end
else
#user.errors.full_messages
flash[:error] = #user.errors.full_messages
render :edit
end
end
private
def online_params
params.require(:online).permit(:user_id, :post_id, :prix, :portion, :push, :pushed_at)
end
def owned_online
#post = Post.find(params[:post_id])
unless current_user == #post.user
flash[:alert] = "That post doesn't belong to you!"
redirect_to :back
end
end
def set_post
#post = Post.find_by(params[:post_id])
end
def set_online
#post = Post.find(params[:post_id])
#online = Online.find_by(params[:id])
end
end
Posts :
class PostsController < ApplicationController
before_action :authenticate_user!
before_action :set_post, only: [:show, :edit, :update, :destroy]
before_action :set_online
before_action :owned_post, only: [:edit, :update, :destroy]
# GET /posts
# GET /posts.json
def index
#posts = Post.push_posts
end
# GET /posts/1
# GET /posts/1.json
def show
end
# GET /posts/new
def new
#post = current_user.posts.build
end
# GET /posts/1/edit
def edit
end
# POST /posts
# POST /posts.json
def create
#post = current_user.posts.build(post_params)
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: #post }
else
format.html { render :new }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /posts/1
# PATCH/PUT /posts/1.json
def update
respond_to do |format|
if #post.update(post_params)
format.html { redirect_to #post, notice: 'Post was successfully updated.' }
format.json { render :show, status: :ok, location: #post }
else
format.html { render :edit }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
#post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:user_id, :title, :description, :image, ingredients_attributes: [:id, :name, :_destroy])
end
def owned_post
unless current_user == #post.user
flash[:alert] = "That post doesn't belong to you!"
redirect_to root_path
end
end
def set_online
#onlines = Online.find_by(params[:id])
end
end
Models
Online :
class Online < ActiveRecord::Base
belongs_to :post
belongs_to :user
scope :push, ->{ where(push: true).order("pushed_at DESC") }
end
Post :
class Post < ActiveRecord::Base
belongs_to :user
has_many :onlines, dependent: :destroy
scope :push_posts, lambda { joins(:onlines).merge(Online.push) }
has_many :ingredients, dependent: :destroy
accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true
has_many :comments
validates :image, presence: true
has_attached_file :image, styles: { medium: "300x300#"}, default_url: "/images/:style/missing.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
& finaly, the view to display the index of post :
<div class="row">
<%- #posts.each do |post|%>
<%- if post.onlines.last.push == true %>
<div class="post">
<div class="form-group text-center">
<h3> <%=post.title%></h3>
</div>
<p> Posted by : <%= link_to post.user.pseudo, profile_path(post.user.pseudo) %>, <%= time_ago_in_words(post.onlines.last.pushed_at) %> ago </p>
<p><%= post.onlines.last.prix %></p>
<p><%= post.onlines.last.portion %></p>
<div class="image text-center">
<div class="image-border">
<%= link_to (image_tag post.image.url(:medium), class: 'img-responsive'), post_path(post)%>
</div>
</div>
</div>
<% end %>
<%end%>
</div>
</div>
</div>
Thanks for your times !!
You probably would put it into the controller action where you can use
YourModel.where(post_id: params[:post_id]).update_all(push: false)
or something similar. It kind of depends what you want to do if you create more than 2 items with the same post_id
Vehicles_controller.rb
class VehiclesController < ApplicationController
before_action :set_vehicle, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
# skip_before_action :verify_authenticity_token
# GET /vehicles
# GET /vehicles.json
def index
#q = Vehicle.search(params[:q])
#vehicles = #q.result(:distinct => true).order_by([:updated_at, :desc]).page(params[:page]).per(5)
#vehicle = Vehicle.new
end
# GET /vehicles/1
# GET /vehicles/1.json
def show
end
# GET /vehicles/new
def new
end
# GET /vehicles/1/edit
def edit
end
# POST /vehicles
# POST /vehicles.json
def create
params[:vehicle][:name] = params[:vehicle][:name].upcase if !params[:vehicle][:name].nil?
#vehicle = Vehicle.new(vehicle_params)
#vehicles = Vehicle.all.order_by([:updated_at, :desc]).page(params[:page]).per(5)
respond_to do |format|
if #vehicle.save
format.html { redirect_to :back, notice: 'Vehicle was successfully created.' }
format.json { render action: 'index', status: :created, location: #vehicle }
format.js
else
format.js
format.html { render action: 'new' }
format.json { render json: #vehicle.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /vehicles/1
# PATCH/PUT /vehicles/1.json
def update
params[:vehicle][:name] = params[:vehicle][:name].upcase if !params[:vehicle][:name].nil?
respond_to do |format|
if #vehicle.update(vehicle_params)
format.html { redirect_to #vehicle, notice: 'Vehicle was successfully updated.' }
format.json {render json: #vehicle, status: :ok}
else
format.html { render action: 'edit' }
format.json { render json: #vehicle.errors, status: :unprocessable_entity }
end
end
end
# DELETE /vehicles/1
# DELETE /vehicles/1.json
def destroy
#vehicle.destroy
respond_to do |format|
format.html { redirect_to vehicles_url, notice: "#{#vehicle.name} deleted successfully" }
format.json { head :no_content }
format.js { render :layout => false}
end
end
def vehicle_search
#q = Vehicle.search(params[:q])
#vehicles = #q.result(:distinct => true).order_by([:updated_at, :desc]).page(params[:page]).per(5)
respond_to do |format|
format.html
format.js
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_vehicle
#vehicle = Vehicle.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def vehicle_params
params.require(:vehicle).permit(:name, :created_at, :updated_at)
end
end
index.html.erb
<% #vehicles.each do |vehicle| %>
<tr>
<td><%= best_in_place vehicle,:name, class: "v_name", id: vehicle.id%></td>
<td><%= link_to '<i class="fa fa-trash-o"></i>'.html_safe, vehicle, method: :delete, remote: true, data: { confirm: "Are you sure to delete <b>\"#{vehicle.name}\"?</b>", commit: "OK" }, title: "Delete Vehicle", class: "btn btn-danger delete_vehicle" %>
</td>
</tr>
<%end%>
vehicle.rb
class Vehicle
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
validates :name, presence: true, uniqueness: true, :format => {:with => /[1-9a-zA-Z][0-9a-zA-Z ]{3,}/}
has_many :pre_processings
has_many :batch_counts
end
destroy.js.erb
$('.delete_vehicle').bind('ajax:success', function() {
$(this).closest('tr').fadeOut();
});
$(".alert").show();
$(".alert").html("Vehicle \"<b><%=#vehicle.name %></b>\" deleted successfully.")
$(".alert").fadeOut(5000);
Here i am using destroy.js.erb to delete vehicle name. It works fine.
Here i am using Inline Edit for Best_in_place. After update the Vehicle name, The ajax alert shows previous vehicle name. Not update vehicle name. So how to show updated vehicle name alert.
$(".alert").html("Vehicle \"<b><%=#vehicle.name %></b>\" deleted successfully.")
The above alert i will show current vehicle name to delete. But if i update using inline edit after i want to delete i'll shows previous record.
Example:
Vehicle Name: MH P5 2312 , I want to delete it, The alert shows are you delete "MH P5 2312 " Vehicle.
After inline edit i will change Vehicle Name: AP 16 1234, So i want to delete Vehicle Name: AP 16 1234, but the ajax alert shows, Vehicle Name: MH P5 2312 delete vehicle name.
Advance Thanks.
This is because you need to update the alert message on ajax request success
in your destroy.js.erb
you should ditch the .erb and fetch the car name from an html element instead
your js code should be as the following:
$('.delete_vehicle').bind('ajax:success', function() {
var vehicleName = $('vehicle_link').data('vehicle_name');
// here I assume that you have a link for initiating the delete process and you can add an attribute to this anchor tag element called data-vehicle_name and set its value to the car name.
$(this).closest('tr').fadeOut();
$(".alert").show();
$(".alert").html("Vehicle \"<b>" + vehicleName + "</b>\" deleted successfully.");
$(".alert").fadeOut(5000);
});
Firstly, if you're going to use the ajax:success callback (which you don't in this instance), you'll need to bind the alert functions to it:
$('.delete_vehicle').on('ajax:success', function() {
$(this).closest('tr').fadeOut();
$(".alert").show().html("Vehicle \"<b><%=#vehicle.name %></b>\" deleted successfully.").fadeOut(5000);
});
Secondly, if you're not getting an updated #vehicle.name because - I think - your Rails instance will have already rendered it. I'm not exactly sure why, but the key will be to pass your data through the ajax request if you were still going to use it:
#app/controllers/vehicles_controller.rb
class VehiclesController < ApplicationController
def destroy
...
format.js { render :layout => false, json: #vehicle }
end
end
#app/assets/javascripts/application.js
$('.delete_vehicle').on('ajax:success', function(event, data, status, xhr) {
vehicle = JSON.parse(data);
$(this).closest('tr').fadeOut();
$(".alert").show().html("Vehicle \"<b>" + + "</b>" deleted successfully.").fadeOut(5000);
});
--
Bottom line is that js.erb is meant to give you actionable Javascript functionality from the controller action. I think your main problem is you're using ajax within this, likely causing a conflict.
Above is how I'd use Ajax (IE put the code in the javascript assets folder); if you wanted to use destroy.js.erb still, you could use the following:
#app/views/vehicles/destroy.js.erb
$("<%= #vehicle.id %>").closest('tr').fadeOut();
$(".alert").show();
$(".alert").html("Vehicle \"<b><%=#vehicle.name %></b>\" deleted successfully.")
$(".alert").fadeOut(5000);