Rails 6 - Sortable - javascript

I have a problem with HTML sortable update in rails 6
I want to drag and drop the images through web page and that is worked fine but, When I want to update the order I got 404 not found error in console log and also an error in find ID.
by the way, I use this script for HTML sortable
https://github.com/jordanhudgens/devcamp-portfolio/blob/master/app/assets/javascripts/html.sortable.js
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 , :sort]}, site_admin: :all
def index
# You can filter what you want to show in protfolio
# Portfolio.where(subtitle: "Angular")
# You can define it in models and call the method here
# It must create on Portfolio.rb in models
# You can create scope too on models and call
#portfolio_items = Portfolio.by_position
end
def angular
#angular_portfolio_items = Portfolio.angular
end
def sort
params[:order].each do |key, value|
Portfolio.find(value[:id]).update(position: value[:position])
end
head :ok
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: 'Portfolio was successfully created.' }
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 was successfully updated.' }
else
format.html { render :edit }
end
end
end
def show
end
def destroy
# Perform the lookup
# Destroy/delete the record
#portfolio_item.destroy
#Redirect
respond_to do |format|
format.html { redirect_to portfolios_url, notice: 'Portfolio was successfully deleted!.' }
end
end
private
def portfolio_params
params.require(:portfolio)
end
def set_portfolio_item
#portfolio_item = Portfolio.find(params[:id])
end
end
This is my 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 'portfolio/:id' , to: 'portfolios#show', as: 'portfolio_show'
get 'angular-items' , to: 'portfolios#angular'
# we can pass anything here after get
get 'about', to: 'pages#about'
get 'contact', to: 'pages#contact'
resources :blogs do
member do
get :toggle_status
end
end
resources :posts
root to: 'pages#home'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
This is my CoffeeScript for HTML sortable
ready = undefined
set_positions = undefined
set_positions = ->
$('.card').each (i) ->
$(this).attr 'data-pos', i + 1
return
return
ready = ->
set_positions()
$('.sortable').sortable()
$('.sortable').sortable().bind 'sortupdate', (e, ui) ->
updated_order = []
set_positions()
$('.card').each (i) ->
updated_order.push
id: $(this).data('id')
position: i + 1
return
$.ajax
type: 'PUT'
url: '/portfolios/sort'
data: order: updated_order
return
return
$(document).ready ready
Thanks for your helps!

Related

Rails 5.1.2 Ajax remote: true not working

I would like to implement ajax to create a post, without recharging the page and not going to the show (I following a tutorial) but is not working.
in the _form.html.haml you can see remote:true in the form helper
= form_for #post,remote: true do |f|
- if #post.errors.any?
#error_explanation
%h2= "#{pluralize(#post.errors.count, "error")} prohibited this post
from being saved:"
%ul
- #post.errors.full_messages.each do |message|
%li= message
.mdl-textfield.mdl-js-textfield.full-width
= f.text_area :body, class:"mdl-textfield__input"
= f.label :body, "Comparte con la Comunidad", class:"mdl-
textfield__label"
.actions.text-right
= f.submit 'Publicar', class:"mdl-button mdl-js-button mdl-button--
raised mdl-button--colored"
however when the post is created, the application redirect to the show of the post created recently in html format, it should be stay in the form.
I don't know if the version of Rails 5.1.2 has a issue, but in Rails 4 with only typing remote: true the application stay in the form after the submit action.
post controller:
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
# GET /posts
# GET /posts.json
def index
#posts = Post.all
end
# GET /posts/1
# GET /posts/1.json
def show
end
# GET /posts/new
def new
#post = Post.new
end
# GET /posts/1/edit
def edit
end
# POST /posts
# POST /posts.json
def create
#post = current_user.posts.new(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(:body)
end
end
also I have a show.js.erb file to render a view to see the body of the post after he is created.
show.js.erb
$('#posts').append("<%= render j #post %>")
_post.haml
%article
=post.body
Done! in the post controller is missing to respond a JS format and the show.js.erb the render method has bad syntax
1) post controller: add format.js
def create
#post = current_user.posts.new(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 }
format.js { render :show }
else
format.html { render :new }
format.json { render json: #post.errors, status: :unprocessable_entity }
format.js { }
end
end
end
2) show.js.erb: the J it should be before render
$("posts").append(<%= j render #post %>)

Rails 5 ActionCable Not Receiving Data received method not called

When I post a new comment in the product page, an alert should appear to all the users that are logged in and in that page, also the comment should appear without refreshing the page.
When there's incoming data on the websocket for this channel ProductChannel the function received in product.js should be called, but instead nothing happens. Any ideas what could be the problem?
App.product = App.cable.subscriptions.create("ProductChannel", {
connected: function() {
// Called when the subscription is ready for use on the server
},
disconnected: function() {
// Called when the subscription has been terminated by the server
},
received: function(data) {
// Called when there's incoming data on the websocket for this channel
$('.alert.alert-info').show().delay(3000).fadeOut('slow');
$('.product-reviews').prepend(data.comment);
$("#average-rating").attr('data-score', data.average_rating);
refreshRating();
},
listen_to_comments: function(){
return this.perform('listen', {
product_id: $("[data-product-id]").data("product-id")
});
}
});
$(document).on('turbolinks:load', function() {
App.product.listen_to_comments();
});
product_channel.rb
class ProductChannel < ApplicationCable::Channel
def subscribed
# stream_from "some_channel"
# stream_from "product_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def listen(data)
stop_all_streams
stream_for data["product_id"]
end
end
comments_controller.rb
class CommentsController < ApplicationController
def index
redirect_to root_path
end
def create
#product = Product.find(params[:product_id])
#comment = #product.comments.new(comment_params)
#comment.user = current_user
respond_to do |format|
if #comment.save
ProductChannel.broadcast_to #product.id, comment: CommentsController.render(partial: 'comments/comment', locals: {comment: #comment, current_user: current_user}), average_rating: #product.average_rating
format.html { redirect_to #product, notice: 'Review was created successfully.' }
format.json { render :show, status: :created, location: #product }
format.js
else
format.html { redirect_to #product, alert: 'Review was not saved successfully.' }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
Also I get this error Unable to process ProductChannel#listen({"product_id"=>9})

My rails form is not working with has_scope

(I have been coding for barely a month so apologies if it's a stupid question). I have a user model just with name, email and type. I have created an index form that you can filter by type and it should show the results.
Form and filters show as expected by I have 2 problems:
1. The usertype is duplicated. For example, if I have 5 users (created with the faker gem) each one of them is customer or supplier, the filter shows customer and supplier 5 times instead of twice
2. When I select a filter, it all results are shown and they are not filtered.
This is my model:
class User < ActiveRecord::Base
has_many :microposts
scope :by_userType, -> userType { where(:userType => userType) }
This is my Controller
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
has_scope :by_userType, type: :array #, :using => [:userType]
# GET /users
# GET /users.json
#def index
# #users = User.all
#end
def index
#users = apply_scopes(User).all
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
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 parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:name, :email, :userType)
end
end
This is my form:
<p id="notice"><%= notice %></p>
<h1>Listing Users</h1>
<%= form_tag users_path, method: 'get', id: "users_search" do%>
<% #users = User.all %>
<% #users.each do |user|%>
<%= check_box_tag "by_userType[]", user.userType %><%= user.userType %><br>
<% end %>
<%= submit_tag "submit" %>
<% end %>
<div id="users"><%= render 'user_list' %></div>
<script type="text/javascript">
$(function () {
$('input[type=checkbox]').change(function(){
$.get($('#users_search').attr('action'),
$('#users_search').serialize(), null, 'script');
return false;
});
$('users_search').submit(function() {
$.get(this.action, $(this).serialize(), null, 'script');
return false;
});
});
</script>
Thank you in advance for your time!
So a couple of things here. First of all, welcome to rails, and welcome to Stack Overflow.
+1 for asking a question and providing code examples for what you've done so far.
Please note that for standardization, case is important in rails. For declaration of scopes you should use snake case. UserModel is the class name, user_model would be snake case.
Now as far as the actual implementation, I would do it somewhat differently. If you notice most of the ajax-filtering of one model based on a field doesn't use the same model as the parameter, it's not hte ONLY way, but I prefer it, as it allows flexibility for adding extra fields to user_type later. Meaning, if you extract user type into it's own model, then you can easily filter your users from the user_type attribute of :name.
So your user model would have:
class User < ActiveRecord::Base
has_many :microposts
belongs_to :user_type
scope :by_user_type, -> user_type { where(:user_type => user_type) }
end
Then create a new model called user_model
rails g scaffold user_model name:string slug:string avatar:string
** Note that the additional fields are just examples, name is hte only necessary one. But if you want to let users do url searches, the slug is easy to use. i.e. yoursite.com/user_type/sellers
Now create a migration to remove your existing userType field in users and a new one for the relationship.
rails g migration modify_user_type_in_user
And the contents of that file would be
class ModifyUserTypeInUser < ActiveRecord::Migration
def change
remove_column :users, :userType
add_reference :users, :user_type, index: true
end
end
Now edit the new user_type.rb model and add the relationship for users
class UserType < ActiveRecord::Base
has_many :users
end
You also need to use UJS, which you didn't mention in your post. When your form field is clicked on, it's sending a javascript (ajax) request. This means that in order to change the data, you'll need a javascript response template.
So add the file app/views/users/index.js.erb and put inside it these contents:
$("#users").html('<%= j(render("user_list", users: #users)) %>');
$("table tbody tr:nth-of-type(even)").css("background","#BD9FB1");
Lastly, you'll need to change your form, so it represents the correct searchable model. So edit 'app/views/users/index.html.erb'
<p id="notice"><%= notice %></p>
<h1>User Filter</h1>
<%= form_tag users_path, method: 'get', id: "users_search" do%>
<% #user_types = UserType.all %>
<% #user_types.each do |user_type|%>
<%= check_box_tag "by_user_type[]", user_type.id %><%= user_type.name %><br>
<% end %>
<%= submit_tag "submit" %>
<% end %>
<div id="users"><%= render 'user_list' %></div>
<script type="text/javascript">
$(function () {
$('input[type=checkbox]').change(function(){
$.get($('#users_search').attr('action'),
$('#users_search').serialize(), null, 'script');
return false;
});
$('users_search').submit(function(e) {
e.preventDefault();
$.get(this.action, $(this).serialize(), null, 'script');
return false;
});
});
</script>

AJAX not rendering update prior to manual page refresh

I'm working through Agile Web Development with Rails 4, stuck on Chapter 11, Iteration F4. The goal of the section is to have a shopping cart div display only when there are items in the cart, otherwise hide it via display: none. The cart does properly hide itself when the Empty Cart button is clicked, but when an item is then added to it, the cart doesn't display unless the page is then manually refreshed.
Here's what the server output looks like when an item is added to an empty cart:
Started POST "/line_items?product_id=2" for ::1 at 2015-05-10 18:51:44 -0700
Processing by LineItemsController#create as JS
Parameters: {"authenticity_token"=>"v2zcRr2CPsfZP3/qI8l5m0HWdDoOiiyl5oiZxvpYKXp7K2ecXizzCZA37DLm7PwYuSAgemogwjjnDHz4NbavGA==", "product_id"=>"2"}
Cart Load (0.2ms) SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1 [["id", 21]]
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT 1 [["id", 2]]
LineItem Load (0.1ms) SELECT "line_items".* FROM "line_items" WHERE "line_items"."cart_id" = ? AND "line_items"."product_id" = ? LIMIT 1 [["cart_id", 21], ["product_id", 2]]
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "line_items" ("product_id", "cart_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["product_id", 2], ["cart_id", 21], ["created_at", "2015-05-11 01:51:44.341300"], ["updated_at", "2015-05-11 01:51:44.341300"]]
(1.1ms) commit transaction
LineItem Load (0.2ms) SELECT "line_items".* FROM "line_items" WHERE "line_items"."cart_id" = ? [["cart_id", 21]]
Product Load (0.2ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT 1 [["id", 2]]
Rendered line_items/_line_item.html.erb (2.0ms)
Rendered carts/_cart.html.erb (6.7ms)
Rendered line_items/create.js.erb (8.9ms)
And here's what the output looks like when I refresh:
Started GET "/" for ::1 at 2015-05-10 18:57:17 -0700
Processing by StoreController#index as HTML
Cart Load (0.1ms) SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1 [["id", 21]]
Product Load (2.2ms) SELECT "products".* FROM "products" ORDER BY "products"."updated_at" DESC LIMIT 1
Product Load (0.2ms) SELECT "products".* FROM "products" ORDER BY "products"."title" ASC
Rendered store/index.html.erb within layouts/application (17.9ms)
LineItem Exists (0.2ms) SELECT 1 AS one FROM "line_items" WHERE "line_items"."cart_id" = ? LIMIT 1 [["cart_id", 21]]
LineItem Load (0.2ms) SELECT "line_items".* FROM "line_items" WHERE "line_items"."cart_id" = ? [["cart_id", 21]]
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT 1 [["id", 2]]
Rendered line_items/_line_item.html.erb (1.6ms)
Rendered carts/_cart.html.erb (6.2ms)
Completed 200 OK in 129ms (Views: 124.7ms | ActiveRecord: 3.0ms)
Here's my LineItemsController, containing the create action triggered when I add the item to the empty cart:
class LineItemsController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:create]
before_action :set_line_item, only: [:show, :edit, :update, :destroy]
# GET /line_items
# GET /line_items.json
def index
#line_items = LineItem.all
end
# GET /line_items/1
# GET /line_items/1.json
def show
end
# GET /line_items/new
def new
#line_item = LineItem.new
end
# GET /line_items/1/edit
def edit
end
# POST /line_items
# POST /line_items.json
def create
product = Product.find(params[:product_id])
#line_item = #cart.add_product(product.id)
respond_to do |format|
if #line_item.save
format.html { redirect_to store_url }
format.js { #current_item = #line_item }
format.json { render action: 'show', status: :created, location: #line_item }
else
format.html { render action: 'new' }
format.json { render json: #line_item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /line_items/1
# PATCH/PUT /line_items/1.json
def update
respond_to do |format|
if #line_item.update(line_item_params)
format.html { redirect_to #line_item, notice: 'Line item was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #line_item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /line_items/1
# DELETE /line_items/1.json
def destroy
#line_item.destroy
respond_to do |format|
format.html { redirect_to line_items_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_line_item
#line_item = LineItem.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def line_item_params
params.require(:line_item).permit(:product_id)
end
end
And this is my StoreController, containing the index action triggered by the manual refresh:
class StoreController < ApplicationController
include CurrentCart
before_action :set_cart
def index
#products = Product.order(:title)
end
end
It seems that when I empty the cart and inspect the div, the display: none attribute is applied (as it should be) from application.html.erb:
<!DOCTYPE html>
<html>
<head>
<title>Pragprog Books Online Store</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body class='<%= controller.controller_name %>'>
<div id="banner">
<%= image_tag("logo.png") %>
<%= #page_title || "Pragmatic Bookshelf" %>
</div>
<div id="columns">
<div id="side">
<%= hidden_div_if(#cart.line_items.empty?, id: 'cart') do %>
<%= render #cart %>
<% end %>
<ul>
<li>Home</li>
<li>Questions</li>
<li>News</li>
<li>Contact</li>
</ul>
</div>
<div id="main">
<%= yield %>
</div>
</div>
</body>
</html>
The hidden_div_if method is in ApplicationHelper.rb:
module ApplicationHelper
def hidden_div_if(condition, attributes = {}, &block)
if condition
attributes["style"] = "display: none"
end
content_tag("div", attributes, &block)
end
end
But when I inspect the cart div after adding an item, display: none is still applied. What am I missing?
If it matters, here's my CartsController:
class CartsController < ApplicationController
before_action :set_cart, only: [:show, :edit, :update, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
# GET /carts
# GET /carts.json
def index
#carts = Cart.all
end
# GET /carts/1
# GET /carts/1.json
def show
end
# GET /carts/new
def new
#cart = Cart.new
end
# GET /carts/1/edit
def edit
end
# POST /carts
# POST /carts.json
def create
#cart = Cart.new(cart_params)
respond_to do |format|
if #cart.save
format.html { redirect_to #cart, notice: 'Cart was successfully created.' }
format.json { render :show, status: :created, location: #cart }
else
format.html { render :new }
format.json { render json: #cart.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /carts/1
# PATCH/PUT /carts/1.json
def update
respond_to do |format|
if #cart.update(cart_params)
format.html { redirect_to #cart, notice: 'Cart was successfully updated.' }
format.json { render :show, status: :ok, location: #cart }
else
format.html { render :edit }
format.json { render json: #cart.errors, status: :unprocessable_entity }
end
end
end
# DELETE /carts/1
# DELETE /carts/1.json
def destroy
#cart.destroy if #cart.id == session[:cart_id]
session[:cart_id] = nil
respond_to do |format|
format.html { redirect_to store_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cart
#cart = Cart.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cart_params
params[:cart]
end
def invalid_cart
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to store_url, notice: 'Invalid cart'
end
end
After a couple of days of spinning my wheels, I finally noticed that the jQuery selectors in my create.js.erb were missing the #, i.e.:
if ($('cart tr').length == 1) {
$('cart').show('blind', 1000);
}
Instead of:
if ($('#cart tr').length == 1) {
$('#cart').show('blind', 1000);
}
Adding them fixed it.

Table disappears after AJAX function has run

For some reason after a click my button that requests data from my controller, my table disappears. Here is my table:
<div id="SelectedTm" style= float:right>
<table id = "PlyrsTm2" style = float:right>
<tr><th id="PTTitle" colspan=2>List of players on selected team</th></tr>
<tr><th id="PTHRows">Player</th><th id="PTHRows">Team</th></tr>
<% #pl.each do |f| %>
<tr><td class="player"><%= f.Plyr %></td><td class="team"><%= f.Team%></td></tr>
<% end %>
</table>
</div>
Here is the button that triggers my jquery with ajax
<button id="showbtn">Select Team</button>
Here is the jquery and ajax:
$(document).ready(function(){
$('#showbtn').on('click', function() {
ids = $('#teams').val()
IM = false
$.ajax({
url: "http://localhost:3000/teamplayers.json?resolution="+ids+"&import="+IM,
type:"get",
dataType: "json",
cache: true,
success:function(data){
$('#PlyrsTm2').html(data);
alert("Loading Players....");
},
error: function(error) {
alert("Failed " + console.log(error) + " " + error)
}
});
$('#PlyrsTm2').trigger('create');
return false;
});
});
Now as you can see, my table is populated by rails. Every time i select a new team the table disappears. And only re-appears if I reload the page, but that is the originally selected team, which by default is the first one.
UPDATE
Here is my controller:
class TeamplayersController < ApplicationController
before_filter :set_id
before_action :set_id, :set_teamplayer, only: [:show, :edit, :update, :destroy]
# GET /teamplayers
# GET /teamplayers.json
def index
#teamplayers = Teamplayer.all
#fteams = Fteam.all
tid = params[:resolution]
toimport = params[:import]
puts tid
if tid.nil? == true
tid = 1
#ids = tid
#pl = Teamplayer.joins(:live_player).where(:teamid => #ids).all
else
tid = tid.to_i;
#ids = tid
#pl = Teamplayer.joins(:live_player).where(:teamid => #ids).pluck(:Plyr, :Team)
end
if toimport == "true"
#turl = Fteam.where(:id => #ids).pluck(:TeamUrl)
#turl = #turl[0]
system "rake updateTm:updateA[#{#turl},#{#ids}]"
end
end
# GET /teamplayers/1
# GET /teamplayers/1.json
def show
end
# GET /teamplayers/new
def new
#teamplayer = Teamplayer.new
end
# GET /teamplayers/1/edit
def edit
end
# POST /teamplayers
# POST /teamplayers.json
def create
#teamplayer = Teamplayer.new(teamplayer_params)
respond_to do |format|
if #teamplayer.save
format.html { redirect_to #teamplayer, notice: 'Teamplayer was successfully created.' }
format.json { render action: 'show', status: :created, location: #teamplayer }
else
format.html { render action: 'new' }
format.json { render json: #teamplayer.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /teamplayers/1
# PATCH/PUT /teamplayers/1.json
def update
respond_to do |format|
if #teamplayer.update(teamplayer_params)
format.html { redirect_to #teamplayer, notice: 'Teamplayer was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #teamplayer.errors, status: :unprocessable_entity }
end
end
end
# DELETE /teamplayers/1
# DELETE /teamplayers/1.json
def destroy
#teamplayer.destroy
respond_to do |format|
format.html { redirect_to teamplayers_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_teamplayer
#teamplayer = Teamplayer.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def teamplayer_params
params.require(:teamplayer).permit(:playerid, :teamid)
end
end
So what is going wrong here, because i notice that it is calling every records individual page but why is it now giving my back the the information from my query as the data instead?
Looks like the statement ids = $("#teams").val(); will return undefined, since there is no element with id="teams".
If ids is undefined, it's likely that data is null or undefined in this function call:
function(data){
$('#PlyrsTm2').html(data);
alert("Loading Players....");
}
If data is null, calling html(null) will cause all your table data to disappear.
So, the solution is to populate ids correctly. I'm not sure what ids is supposed to do, but that's most likely the solution.
$('#PlyrsTm2').html(data);
That's why your table disappears
The problem is you're replacing the content of this element (not the element itself). To fix this, I'd do this:
$('#SelectedTm').html(data);

Categories

Resources