Friday, June 24, 2016

Rails search form throwing back error Couldn't find Product with 'id'=search | Fixed issues

Rails search form throwing back error Couldn't find Product with 'id'=search | Fixed issues


Rails search form throwing back error Couldn't find Product with 'id'=search

Posted: 24 Jun 2016 07:56 AM PDT

I'm building an rails app to learn ruby on rails.(I'm very unexperienced) I'm trying to implement a search bar to the app.

When I hit search rails throws back this error Couldn't find Product with 'id'=search

in this line # Use callbacks to share common setup or constraints between actions. def set_product @product = Product.find(params[:id]) end

I've been working on this search form for hours and checked out various tutorials and stackoverflow posts trying to figure this out. I'm totally lost but the solution is probably pretty simple. Please can anyone help me.

this is my search form in _navbar.html.erb

    <div class="input-group">        <%= form_tag search_products_path, method: 'get', class: 'navbar-form' do %>        <%= text_field_tag :query, params[:query], placeholder: "Search", class: "form-control"%>      </div>       <span class="input-group-btn">         <%= submit_tag "Search", class: 'btn btn-default' %>      </span>      <% end %>  

This is the products.rb model

class Product < ActiveRecord::Base        mount_uploader :image, ImageUploader      validates_presence_of :name, :price, :stock_quantity    validates_numericality_of :price, :stock_quantity      belongs_to :designer    belongs_to :category    belongs_to :page      def self.search(query)        where("name LIKE ? OR description LIKE ?", "%#{query}%", "%#{query}%")     end     end  

This is the products_controller.rb

 class ProductsController < ApplicationController    before_action :set_product, only: [:show, :edit, :update, :destroy, :search]    before_filter :initialize_cart    before_action :authenticate_admin!, only: [ :new, :edit, :update, :create, :destroy ]    # GET /products    # GET /products.json    def index     @products = Product.all    end      def search        @products = Product.search(params[:query]).order("created_at DESC")      @categories = Category.joins(:products).where(:products => {:id => @products.map{|x| x.id }}).distinct      end      # GET /products/1    # GET /products/1.json    def show      end      # GET /products/new    def new     @product = Product.new    end      # GET /products/1/edit    def edit      end      # POST /products    # POST /products.json    def create      @product = Product.new(product_params)        respond_to do |format|    if @product.save      format.html { redirect_to @product, notice: 'Product was successfully created.' }      format.json { render :show, status: :created, location: @product }    else      format.html { render :new }      format.json { render json: @product.errors, status: :unprocessable_entity }       end     end    end      # PATCH/PUT /products/1    # PATCH/PUT /products/1.json    def update       respond_to do |format|         if @product.update(product_params)           format.html { redirect_to @product, notice: 'Product was successfully updated.' }           format.json { render :show, status: :ok, location: @product }         else           format.html { render :edit }           format.json { render json: @product.errors, status: :unprocessable_entity }         end       end     end       # DELETE /products/1     # DELETE /products/1.json     def destroy       @product.destroy       respond_to do |format|       format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }       format.json { head :no_content }     end   end     private      # Use callbacks to share common setup or constraints between actions.      def set_product       @product = Product.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.     def product_params       params.require(:product).permit(:name, :description, :price, :image, :category_id, :stock_quantity, :designer_id, :query)     end   end  

this is views/products/search.html.erb

 <table class="table table-hover">     <thead>       <tr>         <th>Name</th>         <th>Description</th>         <th>Designer</th>         <th>Price</th>         <th>Stock</th>         <th>Image</th>        </tr>     </thead>     <tbody>     <% @products.each do |product| %>         <tr>          <td><%= link_to product.name, product %></td>          <td><%= product.description %></td>          <td><%= product.designer.designer_name %></td>            <td><%= number_to_currency product.price %></td>          <td><%= product.stock_quantity %></td>            <td><%= image_tag product.image.thumb %></td>          <% end %>     </tr>   </tbody>  

and in routes.rb I have

 Rails.application.routes.draw do    get 'pages/index'      get 'pages/about'      get 'pages/location'      get 'pages/stockists'      devise_for :users     resources :categories     resources :categories     resources :designers     resources :category_names     resources :products         resource :cart, only: [:show] do      post "add", path: "add/:id", on: :member     get :checkout    end      resources :orders, only: [ :index, :show, :create, :update ] do      member do       get :new_payment        post :pay      end    end      post 'products/search' => 'products#search', as: 'search_products'     root 'pages#index'    end  

Rails -- Heroku error even after migration

Posted: 24 Jun 2016 07:55 AM PDT

When I go to the new post page it shows me this error:

We're sorry, but something went wrong.    If you are the application owner check the logs for more information.  

So I checked the logs:

$ heroku logs  2016-06-24T14:39:23.117032+00:00 app[web.1]:  2016-06-24T14:39:23.114700+00:00 app[web.1]:   User Load (0.7ms)  SELECT  "users  ".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["  id", 1]]  2016-06-24T14:39:23.117050+00:00 app[web.1]:  2016-06-24T14:39:22.859142+00:00 heroku[router]: at=info method=GET path="/blog_  posts/new" host=hisaan.herokuapp.com request_id=61e39667-302f-42c7-b54b-c111a6e7  4d71 fwd="51.36.189.186" dyno=web.1 connect=1ms service=24ms status=500 bytes=17  54  2016-06-24T14:39:23.120773+00:00 heroku[router]: at=info method=GET path="/blog_  posts/new" host=hisaan.herokuapp.com request_id=d2f95813-1b76-409d-a9f7-a78ad625  be69 fwd="51.36.189.186" dyno=web.1 connect=1ms service=14ms status=500 bytes=17  54  2016-06-24T14:40:33.236242+00:00 heroku[api]: Starting process with command `bun  dle exec rake db:migrate` by the-cuboid@hotmail.com  2016-06-24T14:40:37.069491+00:00 heroku[run.9307]: Awaiting client  2016-06-24T14:40:37.096467+00:00 heroku[run.9307]: Starting process with command   `bundle exec rake db:migrate`  2016-06-24T14:40:37.160101+00:00 heroku[run.9307]: State changed from starting t  o up  2016-06-24T14:40:41.822801+00:00 heroku[run.9307]: Process exited with status 0  2016-06-24T14:40:41.839281+00:00 heroku[run.9307]: State changed from up to comp  lete  2016-06-24T14:41:07.887878+00:00 app[web.1]: Started GET "/blog_posts/new" for 5  1.36.189.186 at 2016-06-24 14:41:07 +0000  2016-06-24T14:41:07.928317+00:00 app[web.1]:  2016-06-24T14:41:07.928328+00:00 app[web.1]: ActiveRecord::UnknownAttributeError   (unknown attribute 'user_id' for BlogPost.):  2016-06-24T14:41:07.928329+00:00 app[web.1]:   app/controllers/blog_posts_contro  ller.rb:19:in `new'  2016-06-24T14:41:07.928330+00:00 app[web.1]:  2016-06-24T14:41:07.893808+00:00 app[web.1]: Processing by BlogPostsController#n  ew as HTML  2016-06-24T14:41:07.900576+00:00 app[web.1]:   User Load (1.1ms)  SELECT  "users  ".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["  id", 1]]  2016-06-24T14:41:07.923473+00:00 app[web.1]: Completed 500 Internal Server Error   in 30ms (ActiveRecord: 1.1ms)  2016-06-24T14:41:07.928331+00:00 app[web.1]:  2016-06-24T14:41:07.934843+00:00 heroku[router]: at=info method=GET path="/blog_  posts/new" host=hisaan.herokuapp.com request_id=8af2d65a-262d-4f25-a988-e4815c60  7bd6 fwd="51.36.189.186" dyno=web.1 connect=1ms service=50ms status=500 bytes=17  54  2016-06-24T14:41:08.198891+00:00 heroku[router]: at=info method=GET path="/favic  on.ico" host=hisaan.herokuapp.com request_id=f99fd00e-cef4-47ad-ae05-07f1590d9d9  2 fwd="51.36.189.186" dyno=web.1 connect=1ms service=13ms status=200 bytes=228  2016-06-24T14:41:57.122890+00:00 app[web.1]: Started GET "/" for 51.36.189.186 a  t 2016-06-24 14:41:57 +0000  2016-06-24T14:41:57.134586+00:00 app[web.1]:   User Load (0.7ms)  SELECT  "users  ".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["  id", 1]]  2016-06-24T14:41:57.166703+00:00 app[web.1]: Completed 200 OK in 41ms (Views: 39  .7ms | ActiveRecord: 0.7ms)  2016-06-24T14:41:57.140708+00:00 app[web.1]:   Rendered pages/_header2.html.erb  (5.8ms)  2016-06-24T14:41:57.125454+00:00 app[web.1]: Processing by PagesController#home  as HTML  2016-06-24T14:41:57.164893+00:00 app[web.1]:   Rendered pages/home.html.erb with  in layouts/application (37.6ms)  2016-06-24T14:41:57.416859+00:00 app[web.1]: Started GET "/assets/1.jpg" for 51.  36.189.186 at 2016-06-24 14:41:57 +0000  2016-06-24T14:41:57.637418+00:00 app[web.1]: Started GET "/assets/com.jpg" for 5  1.36.189.186 at 2016-06-24 14:41:57 +0000  2016-06-24T14:41:57.992607+00:00 app[web.1]: Processing by PagesController#home  as HTML  2016-06-24T14:41:57.995937+00:00 app[web.1]:   User Load (0.7ms)  SELECT  "users  ".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["  id", 1]]  2016-06-24T14:41:57.997175+00:00 app[web.1]:   Rendered pages/_header2.html.erb  (3.2ms)  2016-06-24T14:41:58.006466+00:00 app[web.1]: Completed 200 OK in 14ms (Views: 12  .2ms | ActiveRecord: 0.7ms)  2016-06-24T14:41:57.989773+00:00 app[web.1]: Started GET "/" for 51.36.189.186 a  t 2016-06-24 14:41:57 +0000  2016-06-24T14:41:58.005343+00:00 app[web.1]:   Rendered pages/home.html.erb with  in layouts/application (11.5ms)  2016-06-24T14:41:58.784241+00:00 app[web.1]: Started GET "/assets/1.jpg" for 51.  36.189.186 at 2016-06-24 14:41:58 +0000  2016-06-24T14:41:56.133604+00:00 heroku[router]: at=info method=GET path="/favic  on.ico" host=hisaan.herokuapp.com request_id=974bc304-0647-4a0b-af83-edb058345d3  2 fwd="51.36.189.186" dyno=web.1 connect=1ms service=6ms status=304 bytes=133  2016-06-24T14:41:59.397828+00:00 app[web.1]: Started GET "/assets/com.jpg" for 5  1.36.189.186 at 2016-06-24 14:41:59 +0000  2016-06-24T14:41:57.170670+00:00 heroku[router]: at=info method=GET path="/" hos  t=hisaan.herokuapp.com request_id=3f472261-f90b-4c03-8461-df3b0aa8e626 fwd="51.3  6.189.186" dyno=web.1 connect=1ms service=50ms status=200 bytes=5382  2016-06-24T14:41:57.646756+00:00 heroku[router]: at=info method=GET path="/asset  s/com.jpg" host=hisaan.herokuapp.com request_id=77ccccfd-dd98-4162-9fe8-69cab15b  323c fwd="51.36.189.186" dyno=web.1 connect=1ms service=16ms status=304 bytes=34  3  2016-06-24T14:41:57.422824+00:00 heroku[router]: at=info method=GET path="/asset  s/1.jpg" host=hisaan.herokuapp.com request_id=5cdb1968-2f2d-4ec1-b599-47a4d1be85  9b fwd="51.36.189.186" dyno=web.1 connect=1ms service=11ms status=304 bytes=343  2016-06-24T14:42:00.665895+00:00 app[web.1]: Processing by BlogPostsController#i  ndex as HTML  2016-06-24T14:42:00.673998+00:00 app[web.1]:   User Load (0.7ms)  SELECT  "users  ".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["  id", 1]]  2016-06-24T14:42:00.676600+00:00 app[web.1]:   Rendered blog_posts/index.html.er  b within layouts/application (8.6ms)  2016-06-24T14:42:00.675930+00:00 app[web.1]:   BlogPost Load (1.0ms)  SELECT "bl  og_posts".* FROM "blog_posts"  2016-06-24T14:42:00.678298+00:00 app[web.1]:   Rendered layouts/_header.html.erb   (0.7ms)  2016-06-24T14:42:00.663850+00:00 app[web.1]: Started GET "/blog_posts" for 51.36  .189.186 at 2016-06-24 14:42:00 +0000  2016-06-24T14:42:00.678619+00:00 app[web.1]: Completed 200 OK in 13ms (Views: 9.  8ms | ActiveRecord: 1.6ms)  2016-06-24T14:41:58.011615+00:00 heroku[router]: at=info method=GET path="/" hos  t=hisaan.herokuapp.com request_id=32177ecc-4b74-4b43-b58d-e41af06b3982 fwd="51.3  6.189.186" dyno=web.1 connect=1ms service=25ms status=200 bytes=5382  2016-06-24T14:41:59.637792+00:00 heroku[router]: at=info method=GET path="/asset  s/BME1-8665c4d59a4c5496380d5b5e028f7b88bb2abda9ee6b71839a6b5f253b9c3784.jpg" hos  t=hisaan.herokuapp.com request_id=6e2cf143-2478-4449-aa23-47dc9b0e3a2d fwd="51.3  6.189.186" dyno=web.1 connect=0ms service=4ms status=304 bytes=133  2016-06-24T14:41:58.268652+00:00 heroku[router]: at=info method=GET path="/asset  s/application-25535718b674acd46cb1bbdbfcc682f19a8bab87f1ef54ae3f4b7a5fcc7f2bac.c  ss" host=hisaan.herokuapp.com request_id=5282b136-bed9-4c33-b8b1-798cfefd048e fw  d="51.36.189.186" dyno=web.1 connect=1ms service=6ms status=304 bytes=133  2016-06-24T14:41:58.481250+00:00 heroku[router]: at=info method=GET path="/asset  s/application-7a1792b27fd8e809255833888935d77745f506c1bb953bc302a2fbd0eae460ac.j  s" host=hisaan.herokuapp.com request_id=18e97d75-2957-47d3-8fb0-d71a56da21d7 fwd  ="51.36.189.186" dyno=web.1 connect=1ms service=6ms status=304 bytes=133  2016-06-24T14:41:58.792403+00:00 heroku[router]: at=info method=GET path="/asset  s/1.jpg" host=hisaan.herokuapp.com request_id=1bfac075-6b37-4e7e-aa5b-cefc90be54  ed fwd="51.36.189.186" dyno=web.1 connect=1ms service=11ms status=304 bytes=343  2016-06-24T14:42:01.956878+00:00 app[web.1]: Completed 500 Internal Server Error   in 17ms (ActiveRecord: 0.8ms)  2016-06-24T14:42:01.958696+00:00 app[web.1]:  2016-06-24T14:42:01.958706+00:00 app[web.1]:  2016-06-24T14:42:01.942967+00:00 app[web.1]:   User Load (0.8ms)  SELECT  "users  ".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["  id", 1]]  2016-06-24T14:42:01.937615+00:00 app[web.1]: Started GET "/blog_posts/new" for 5  1.36.189.186 at 2016-06-24 14:42:01 +0000  2016-06-24T14:41:59.414484+00:00 heroku[router]: at=info method=GET path="/image  s/science.png" host=hisaan.herokuapp.com request_id=277151f1-b52b-449f-9c78-7872  54e85992 fwd="51.36.189.186" dyno=web.1 connect=1ms service=29ms status=200 byte  s=183524  2016-06-24T14:42:01.958706+00:00 app[web.1]:   app/controllers/blog_posts_contro  ller.rb:19:in `new'  2016-06-24T14:42:02.180930+00:00 app[web.1]: Started GET "/blog_posts/new" for 5  1.36.189.186 at 2016-06-24 14:42:02 +0000  2016-06-24T14:42:02.183479+00:00 app[web.1]: Processing by BlogPostsController#n  ew as HTML  2016-06-24T14:42:01.958707+00:00 app[web.1]:  2016-06-24T14:42:01.958705+00:00 app[web.1]: ActiveRecord::UnknownAttributeError   (unknown attribute 'user_id' for BlogPost.):  2016-06-24T14:42:01.940083+00:00 app[web.1]: Processing by BlogPostsController#n  ew as HTML  2016-06-24T14:42:02.185989+00:00 app[web.1]:   User Load (0.7ms)  SELECT  "users  ".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["  id", 1]]  2016-06-24T14:42:00.717492+00:00 heroku[router]: at=info method=GET path="/blog_  posts" host=hisaan.herokuapp.com request_id=d03e05e6-6bfb-42ba-a831-1bed9e2f982b   fwd="51.36.189.186" dyno=web.1 connect=1ms service=21ms status=200 bytes=2779  2016-06-24T14:42:02.193743+00:00 app[web.1]:  2016-06-24T14:42:02.193752+00:00 app[web.1]: ActiveRecord::UnknownAttributeError   (unknown attribute 'user_id' for BlogPost.):  2016-06-24T14:42:02.193753+00:00 app[web.1]:   app/controllers/blog_posts_contro  ller.rb:19:in `new'  2016-06-24T14:42:02.193753+00:00 app[web.1]:  2016-06-24T14:42:02.192075+00:00 app[web.1]: Completed 500 Internal Server Error   in 8ms (ActiveRecord: 0.7ms)  2016-06-24T14:42:02.193754+00:00 app[web.1]:  2016-06-24T14:41:59.418876+00:00 heroku[router]: at=info method=GET path="/image  s/comp.gif" host=hisaan.herokuapp.com request_id=b047be70-d8a4-4a50-8322-c6b91b7  31e17 fwd="51.36.189.186" dyno=web.1 connect=1ms service=35ms status=200 bytes=4  33197  2016-06-24T14:41:59.415815+00:00 heroku[router]: at=info method=GET path="/asset  s/com.jpg" host=hisaan.herokuapp.com request_id=c4830791-cc2a-45e2-b321-7c94f2d2  8185 fwd="51.36.189.186" dyno=web.1 connect=0ms service=18ms status=304 bytes=34  3  2016-06-24T14:42:01.961525+00:00 heroku[router]: at=info method=GET path="/blog_  posts/new" host=hisaan.herokuapp.com request_id=5d3da25b-83bf-46b2-8ac7-ab344d20  8949 fwd="51.36.189.186" dyno=web.1 connect=1ms service=28ms status=500 bytes=17  54  2016-06-24T14:42:02.196982+00:00 heroku[router]: at=info method=GET path="/blog_  posts/new" host=hisaan.herokuapp.com request_id=c6841d54-c1b8-4457-bbe0-85f785f8  747d fwd="51.36.189.186" dyno=web.1 connect=1ms service=19ms status=500 bytes=17  54  2016-06-24T14:42:18.083201+00:00 heroku[run.8790]: Awaiting client  2016-06-24T14:42:18.100539+00:00 heroku[run.8790]: Starting process with command   `bundle exec rake db:migrate`  2016-06-24T14:42:18.395002+00:00 heroku[run.8790]: State changed from starting t  o up  2016-06-24T14:42:14.705992+00:00 heroku[api]: Starting process with command `bun  dle exec rake db:migrate` by the-cuboid@hotmail.com  2016-06-24T14:42:22.103750+00:00 heroku[run.8790]: State changed from up to comp  lete  2016-06-24T14:42:22.100884+00:00 heroku[run.8790]: Process exited with status 0  2016-06-24T14:42:39.825222+00:00 heroku[api]: Starting process with command `bun  dle exec rake db:migrate` by the-cuboid@hotmail.com  2016-06-24T14:42:44.488427+00:00 heroku[run.2160]: Awaiting client  2016-06-24T14:42:44.482103+00:00 heroku[run.2160]: State changed from starting t  o up  2016-06-24T14:42:44.543967+00:00 heroku[run.2160]: Starting process with command   `bundle exec rake db:migrate`  2016-06-24T14:42:50.589106+00:00 heroku[run.2160]: Process exited with status 0  2016-06-24T14:42:50.594510+00:00 heroku[run.2160]: State changed from up to comp  lete  2016-06-24T14:43:00.647899+00:00 app[web.1]: ActiveRecord::UnknownAttributeError   (unknown attribute 'user_id' for BlogPost.):  2016-06-24T14:43:00.630141+00:00 app[web.1]: Started GET "/blog_posts/new" for 5  1.36.189.186 at 2016-06-24 14:43:00 +0000  2016-06-24T14:43:00.633319+00:00 app[web.1]: Processing by BlogPostsController#n  ew as HTML  2016-06-24T14:43:00.647892+00:00 app[web.1]:  2016-06-24T14:43:00.647901+00:00 app[web.1]:  2016-06-24T14:43:00.644974+00:00 app[web.1]: Completed 500 Internal Server Error   in 10ms (ActiveRecord: 0.8ms)  2016-06-24T14:43:00.647900+00:00 app[web.1]:   app/controllers/blog_posts_contro  ller.rb:19:in `new'  2016-06-24T14:43:00.647901+00:00 app[web.1]:  2016-06-24T14:43:00.639287+00:00 app[web.1]:   User Load (0.8ms)  SELECT  "users  ".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["  id", 1]]  2016-06-24T14:43:00.650882+00:00 heroku[router]: at=info method=GET path="/blog_  posts/new" host=hisaan.herokuapp.com request_id=64efe2cc-d6f6-482a-9a81-68f20144  9dc8 fwd="51.36.189.186" dyno=web.1 connect=1ms service=27ms status=500 bytes=17  54  2016-06-24T14:43:00.904542+00:00 heroku[router]: at=info method=GET path="/favic  on.ico" host=hisaan.herokuapp.com request_id=54f42ec6-3da5-44e3-93e7-db5b7aeedf2  8 fwd="51.36.189.186" dyno=web.1 connect=1ms service=23ms status=200 bytes=228  

After that I ran rake db:migrate again:

$ heroku run rake db:migrate  Running rake db:migrate on hisaan... up, run.2160  /app/vendor/bundle/ruby/2.2.0/gems/bootstrap-4.0.0.alpha3/lib/bootstrap/version.  rb:2: warning: already initialized constant Bootstrap::VERSION  /app/vendor/bundle/ruby/2.2.0/gems/bootstrap-sass-3.3.6/lib/bootstrap-sass/versi  on.rb:2: warning: previous definition of VERSION was here  /app/vendor/bundle/ruby/2.2.0/gems/bootstrap-4.0.0.alpha3/lib/bootstrap/version.  rb:3: warning: already initialized constant Bootstrap::BOOTSTRAP_SHA  /app/vendor/bundle/ruby/2.2.0/gems/bootstrap-sass-3.3.6/lib/bootstrap-sass/versi  on.rb:3: warning: previous definition of BOOTSTRAP_SHA was here  DEPRECATION WARNING: The configuration option `config.serve_static_assets` has b  een renamed to `config.serve_static_files` to clarify its role (it merely enable  s serving everything in the `public` folder and is unrelated to the asset pipeli  ne). The `serve_static_assets` alias will be removed in Rails 5.0. Please migrat  e your configuration files accordingly. (called from <class:Application> at /app  /config/application.rb:26)    ActiveRecord::SchemaMigration Load (0.8ms)  SELECT "schema_migrations".* FROM  "schema_migrations"  

I couldnt figure what happened it worked fine on the localhost running rails s . Could even make new posts on localhost.

Javascript code not working properly in rails

Posted: 24 Jun 2016 07:59 AM PDT

index.html.erb

<div id="app-back-button">    <%= link_to image_tag("back.png",:border => 0), 'javascript:history.go(-1);' %>  </div>  

Above mentioned code triggers back action when back button is clicked.

index.html.erb

Below mentioned code is used to hide and show the div contents.

<a href="#">LINK</a>    <div id = "test">        <h2>Import Statements</h2>        <%= form_tag import_xvaziris_path, multipart: true do %>      <%= file_field_tag :file %>      <%= submit_tag "Import" %>      <% end %>    </div>      <script language="javascript" type="text/javascript">  $( document ).ready(function() {      $("div#test").hide();      $("a").click(function(event) {          event.preventDefault();          $("div#test").toggle();      });  });  </script>  

Now the problem is that when I click the back button, it triggers hide/show functionality and do not go backwards.

Any suggestions are most welcome.

Thank you in advance.

Database_Cleaner with AR-Octopus not cleaning records

Posted: 24 Jun 2016 07:42 AM PDT

We have a project that is using the AR-Octopus gem using sharded databases. The problem we are running into is that the gem 'database_cleaner' is not cleaning records when using this setup, as we are consistently having leftover records in our test database that cause issues with our test suite.

I found this GitHub gist - https://gist.github.com/nowlinuxing/22ea0ab673a5622eb48d

Here is my database_cleaner config file

# spec/support/database_cleaner.rb    require 'database_cleaner'    RSpec.configure do |config|    config.before(:suite) do     DatabaseCleaner.strategy = :transaction     DatabaseCleaner.clean_with(:truncation)    end      ["master", *Octopus.config[Rails.env].keys].each do |shard|      DatabaseCleaner[:active_record, model: ActiveRecord::Base.using(shard)]    end      config.around(:each) do |example|     DatabaseCleaner.cleaning do      example.run     end    end   end  

Has anyone ever encountered this issue? If so, what did you do to resolve the issue? Just looking for some helpful insight.

ActiveRecord query using a joins and where. How do I build it?

Posted: 24 Jun 2016 07:46 AM PDT

I have this query. I am trying to find a house with no address but with a person with an address. A house belongs to an address and a person has many addresses. A house belongs to a person and a person has many houses.

The model names are House, Person, and Address.

House.joins(:person).where('houses.address.id = ? and persons.address_id = ?', 'nil', 'not nil')  

This query above is wrong but probably what I want. How do I construct it? My SQL isn't very good.

Special characters are not encoded on Amazon RDS (PostgreSQL)

Posted: 24 Jun 2016 07:29 AM PDT

I can not see Turkish special characters on Amazon RDS PostgreSQL database. My development database displays characters properly.

When I connect to RDS instance via pgAdmin, I see ■aja²a³a­a@test.com instead of şajaıaüağaç@test.com.

My server encoding and collate are UTF8 and en_US.UTF-8, respectively.

In database.yml file I set encoding to utf8.

default: &default    adapter: postgresql    encoding: utf8  

There isn't any problem on my development database which is also PostgreSQL.

What am I doing wrong?

Looking for a review of my ActiveRecord relations

Posted: 24 Jun 2016 07:17 AM PDT

I recently just started learning RoR and I am creating a hobby project.

So some quick background: Each customer is identified by an account number. Each product sale has an account number attributed with it and the products table contains all the specific product data.

My question is - with the format I have now, is this the proper way I should be linking these tables? One of the issues I am having is filtering a group of sales based on product major. So say I have a customer and I only want to view product sales where the major is "commercial", how do I go about filtering this data? See the scope I created - but I am not sure how to use it.

class Product < ActiveRecord::Base    has_many :product_sales, :primary_key => :prodnum, :foreign_key => :prodnum    has_many :customers, through: :sales    scope :commercial_products, -> { where(major: 'Commercial') }  end            class ProductSale < ActiveRecord::Base      belongs_to :customer, :foreign_key => :account      belongs_to :product, :foreign_key => :prodnum, :primary_key => :prodnum  end          class Customer < ActiveRecord::Base     has_many :product_sales, :primary_key => :account, :foreign_key => :account     has_many :products, through: :product_sales  end  

and my schema

create_table "customers", force: :cascade do |t|    t.integer  "account"    t.string   "name"    t.datetime "created_at", null: false    t.datetime "updated_at", null: false  end         create_table "product_sales", force: :cascade do |t|        t.integer  "account"        t.string   "month"        t.string   "prodnum"        t.integer  "sales"        t.integer  "qtyshipped"        t.datetime "created_at", null: false        t.datetime "updated_at", null: false   end        create_table "products", force: :cascade do |t|          t.string   "pcatcode"          t.string   "pcatname"          t.string   "major"          t.string   "prodline"          t.string   "brand"          t.string   "tier"          t.string   "prodnum"          t.string   "proddesc"          t.datetime "created_at", null: false          t.datetime "updated_at", null: false  end  

Running tests with color using vim-vroom plugin

Posted: 24 Jun 2016 06:46 AM PDT

I'm using minitest with Rails 4 and vim as my main code editor. To display colors (red or green) when I run my tests I use minitest-reporters gem and it works as I expected.

The problem is when I try to run my tests inside vim with vim-vrooom plugin. They run well but colors are not displayed. Is there any configuration I can set to format test output?

Bring "assets" bundler group back in Rails 4

Posted: 24 Jun 2016 06:45 AM PDT

Not sure why it was removed, but how would I go about adding the "assets" bundler group back into my Gemfile, and having it only be included for asset precomplication on deploy (as well as development etc.)? Basically, to recreate the functionality that was already present in Rails 3.

My rationale is to reduce runtime memory usage, since the gems I would put into that group are only really needed during asset precompilation.

Also, is there any inherent reason why this would be a bad idea? I deploy to Heroku, in case that makes any difference.

Cannot retrieve saved data from activerecord while testing

Posted: 24 Jun 2016 07:41 AM PDT

I am testing a controller. Index just method saves article to activerecord but i cannot get the article from test code.

What am I missing?

Controller

class ArticlesController < ApplicationController    def create        if Article.new(:title => "abc").save          render status: 200, json: ""      else           render status: 500, json: ""      end      end  end  

Test

require 'test_helper'    class ArticlesControllerTest < ActionController::TestCase    test "should get create" do      get :create      assert_response :success      assert_nil Article.where(title: "abc"), "Article nil"      end    end  

I get following result

F    Finished in 0.100930s, 9.9079 runs/s, 19.8157 assertions/s.      1) Failure:  ArticlesControllerTest#test_should_get_index [test/controllers/articles_controller_test.rb:7]:  Article nil.  Expected #<ActiveRecord::Relation [#<Article id: 980190963, title: "abc", created_at: "2016-06-24 13:23:36", updated_at: "2016-06-24 13:23:36">]> to be nil.    1 runs, 2 assertions, 1 failures, 0 errors, 0 skips  

No images and fonts production capistrano (Rails)

Posted: 24 Jun 2016 06:27 AM PDT

Guys, in the local server all works fine, but in the production (EC2 Amazon) some (not all) of my fonts and images dont load ! Can some one help me please?

application.rb

    require File.expand_path('../boot', __FILE__)    # Pick the frameworks you want:  require "active_model/railtie"  require "active_record/railtie"  require "action_controller/railtie"  require "action_mailer/railtie"  require "action_view/railtie"  require "sprockets/railtie"  require 'carrierwave'  require 'carrierwave/orm/activerecord'    # require "rails/test_unit/railtie"    # Require the gems listed in Gemfile, including any gems  # you've limited to :test, :development, or :production.  Bundler.require(*Rails.groups)    module TestApp    class Application < Rails::Application      #adding fonts to assets pipeline      config.assets.paths << Rails.root.join("app", "assets", "fonts")      # Settings in config/environments/* take precedence over those specified here.      # Application configuration should go into files in config/initializers      # -- all .rb files in that directory are automatically loaded.      config.autoload_paths << Rails.root.join('lib')      # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.      # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.      # config.time_zone = 'Central Time (US & Canada)'        # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.      # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]      #config.i18n.default_locale = :ru      config.serve_static_files = true      config.serve_static_assets = true      config.assets.compile = true    end  end  

How do I modify the creation of an associated object when done via accepts_nested_attributes_for for another object?

Posted: 24 Jun 2016 07:38 AM PDT

I have a Job model, that belongs_to :company. Both models belong_to :user (i.e. the current_user).

Job accepts_nested_attributes_for :company.

I have my company attributes on the jobs/_form.html.erb.

But, what is happening is that when the company object is being created, it isn't setting an attribute I want it to (company.user_id).

I am not quite sure how to force it to do that.

This is what the log for this part of the operation looks like:

Company Exists (1.4ms)  SELECT  1 AS one FROM "companies" WHERE ("companies"."id" IS NOT NULL) AND "companies"."slug" = $1 LIMIT $2  [["slug", "phish-me"], ["LIMIT", 1]]    SQL (2.7ms)  INSERT INTO "companies" ("name", "logo", "description", "city", "state", "country", "email", "created_at", "updated_at", "slug") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING "id"  [["name", "Acme Corp"], ["logo", "#<ActionDispatch::Http::UploadedFile:0x007f>"], ["description", "Some random description."], ["city", "Leesburg"], ["state", "Virginia"], ["country", "US"], ["email", "random@email.com"], ["created_at", 2016-06-24 09:50:49 UTC], ["updated_at", 2016-06-24 09:50:49 UTC], ["slug", "acme-corp"]]  

I even tried including a hidden field for the user_id in the company portion of that form and it didn't work.

I added a binding.pry to my Company#Create action and it didn't work - so it seems that's not being called.

I am not quite sure how to modify that Create event and ensure that company.user = job.user

How do I do that?

Storing passwords in a database

Posted: 24 Jun 2016 06:38 AM PDT

There are many questions on SO about how to store passwords in a database and i'm aware passwords should under no circumstances be stored in plain text. However, my application requires authentication against various third parties, such as SMB or REST APIs that don't provide OAUTH. In short: i need to store passwords.

To avoid storing passwords in clear text, my idea is to store a secret key in an environment variable and use that for encrypting / decrypting the passwords.

Is that a good approach for the problem or are there any better options?

Rails + aws-sk + S3 Object metadata multiple update

Posted: 24 Jun 2016 05:35 AM PDT

I'm currently trying to work out the best way to update multiple S3 Objects MetaData within a single form.

Has anyone done this before or have any suggestions on how I could accomplish this?

I upload the files manually but wish to update some metadata i add when I upload manually. e.g. x-amz-meta-friendly-title, x-amz-meta-description, x-amz-meta-active

Any guidance is much appreciated.

How to restrict current_user from adding more than 3 order_items to a order per time period?

Posted: 24 Jun 2016 06:35 AM PDT

I'm building a store in Rails that has a specific sales model. I need to allow a user to add only 3 items to his order per 30 days. The 30 days counter should start upon adding the first order_item. Once 30 days expires, user would be able to add 3 orders. If 30 days didn't pass and for an example, user adds two order_items he would still be allowed to add one more order_item within 30 days. So as well if user tries to add more then 3 items to show an error message and disregard saving of the order_items to current_user's order.

I have products, orders, order_items, users. I guess that I should add something to user model but I'm not sure what.

order_items_controller.rb

def create      @order = current_order      @order_item = @order.order_items.new(order_item_params)      @order.user_id = current_user.id      @order.save      session[:order_id] = @order.id      respond_to do |format|      format.js { flash[:notice] = "ORDER HAS BEEN CREATED." }     end    end  private    def order_item_params      params.require(:order_item).permit(:quantity, :product_id, :user_id)    end  end  

user.rb

class User < ActiveRecord::Base    has_many :identities, dependent: :destroy    has_many :order    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :omniauthable, :invitable, :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable  end  

order_item.rb

class OrderItem < ActiveRecord::Base    belongs_to :product    belongs_to :order      validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 }    validate :product_present    validate :order_present      before_save :finalize      def unit_price      if persisted?        self[:unit_price]      else        product.price      end    end      def total_price      unit_price * quantity    end    private    def product_present      if product.nil?        errors.add(:product, "is not valid or is not active.")      end    end      def order_present      if order.nil?        errors.add(:order, "is not a valid order.")      end    end      def finalize      self[:unit_price] = unit_price      self[:total_price] = quantity * self[:unit_price]    end  end  

order.rb

class Order < ActiveRecord::Base    belongs_to :order_status    has_many :order_items    before_create :set_order_status    before_save :update_subtotal      def subtotal      order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.unit_price) : 0 }.sum    end  private    def set_order_status      self.order_status_id = 1    end      def update_subtotal      self[:subtotal] = subtotal    end  end  

Search displaying search results as all products Rails App

Posted: 24 Jun 2016 05:46 AM PDT

I've been working on this search form for an app I'm building to learn Rails.

It's supposed to search for products but when I enter some product name in the search field it gives me a list of all products. The solution is probably simple but I haven't figure it out yet and I'm getting pretty frustrated.

I tried to change @products to a different name but that didn't work.

Can someone check this out and advise me please?

thanks in advance D

in my _navbar the code is

<%= form_tag search_products_path, class: 'navbar-form navbar-right' do %>    <%= search_field_tag class: 'form-control', :id => 'searchbar',  :placeholder =>'Search', :name => "query" %>    <%= submit_tag "Submit", class: 'btn btn-default', :name => nil %>  <% end %>  

in my views/products/search.html.erb

<table class="table table-hover">     <thead>       <tr>        <th>Name</th>        <th>Description</th>        <th>Designer</th>        <th>Price</th>        <th>Stock</th>        <th>Image</th>        </tr>    </thead>     <tbody>    <% @products.each do |product| %>      <tr>      <td><%= link_to product.name, product %></td>      <td><%= product.description %></td>      <td><%= product.designer.designer_name %></td>        <td><%= number_to_currency product.price %></td>      <td><%= product.stock_quantity %></td>        <td><%= image_tag product.image.thumb %></td>       <% end %>  </tr>  </tbody>  

in my product.rb model I have this code

 class Product < ActiveRecord::Base           mount_uploader :image, ImageUploader         validates_presence_of :name, :price, :stock_quantity       validates_numericality_of :price, :stock_quantity         belongs_to :designer       belongs_to :category       belongs_to :page        def self.search(query)        where("name LIKE ? OR description LIKE ?", "%#{query}%", "%#{query}%")       end        end  

In the products_controller.rb I have this code

 def search      @products = Product.search(params[:query])      @categories = Category.joins(:products).where(:products => {:id => @products.map{|x| x.id }}).distinct     end  

Rails Render Multiple in controller Using Json API

Posted: 24 Jun 2016 06:40 AM PDT

I would like to be able to render multiple Json renders in my controller. I have a rails Json API using the Model serializers gem. At the moment I can only render one object. What I would like to do is to also render the @news and @users but right now I'm only rendering the @articles.

Backend Articles controller.rb:

class ArticlesController < ApplicationController  impressionist :actions=>[:show]    # GET /articles    # GET /articles.json    def index      @articles = Article.where(:is_published => true).order('created_at DESC').page(params[:page]).per(6)      @news = Article.where(:news => true)      @users = User.all        respond_to do |format|        format.html # show.html.erb        format.json { render json: @articles.all }      end    end  end  

Backend Article Serializer:

class ArticleSerializer < ActiveModel::Serializer    attributes :id, :title, :teaser_title, :content, :teaser_content, :category, :author, :published, :num_comments, :tags, :featured, :app, :news, :tech, :device, :game, :laptop, :image, :user_id, :is_published, :created_at, :updated_at, :impressionist_count, :previous_post, :next_post, :user_id  end  

Frontend site Article Model:

require 'active_resource'    class Article  < ActiveResource::Base    self.site = "http://localhost:3000"  end  

Frontend Site Articles Controller:

class ArticlesController < ApplicationController    def index      @articles = Article.where(:is_published => true)      @news = Article.where(:is_published => true, :news => true)      @users = User.all    end  end  

Frontend site Article index.html.erb:

<div id='outer-wrapper'>        <div class='margin-1200'>           <div id='content-wrapper'>              <!--Featured Post Home-->              <div class='coverflow section' id='coverflow'>                     <ul id="lightSlider">                     <% @news.each do |news| %>                     <% if news.is_published? %>  <li class="recent-box" style="overflow: hidden; float: left; width: 395px; height: 292px;"><div class="imageContainer"><a target="_top" href="<%= seofy_article_url(news) %>"><img alt="<%= news.title %>" title="<%= news.title %>" src="<%= api_domain_image(news) %>" class="label_thumb"></a></div>  <%= link_to news.title, seofy_article_url(news), :class => "label_title" %>  <div class="toe"><span class="post-date" href="http://socioism.blogspot.com/2015/01/the-year-2015.html"><i class="fa fa-calendar"></i> <%= article_date(news) %></span><span target="_top" href="http://socioism.blogspot.com/2015/01/the-year-2015.html#comment-form" class="recent-com"><i class="fa fa-comment"></i> 12 Comments</span></div></li>    <% else %>  No NEWS!  <% end %>    <% end %>        </ul>              </div>    <div style="clear:both;"></div>  <div class="index">                <div id='main-wrapper'>                 <div class='main section' id='main'>                    <div class='widget Blog' data-version='1' id='Blog1'>                       <div class='blog-posts hfeed'>                          <% @articles.each do |article| %>                          <% if article.is_published? %>                          <div class="date-outer">                             <div class="date-posts">                                <div class='post-outer'>                                   <div class='wrapfullpost'>                                      <div class='post hentry'>                                         <a name='1001054977757960770'></a>                                         <div class='post-header-line-1'></div>                                         <div class='post-body entry-content'>                                            <div class='post-summary' id='summary1001054977757960770'>                                               <div dir="ltr" style="text-align: left;" trbidi="on">                                                  <div dir="ltr" style="text-align: left;" trbidi="on">                                                     <div class="separator" style="clear: both; text-align: left;">                                                        <img border="0" src="<%= api_domain_image(article) %>" />                                                     </div>                                                     <br />                                                  </div>                                                    <div>                                                    </div>                                                 </div>                                            </div>                                              <h2 class='post-title entry-title pagetitle'>                                               <a href='<%= seofy_article_url(article) %>'><%= article.title.first(40) %>...</a>                                            </h2>                                            <div class='post-details'>                                               <span class='post-date'><i class='fa fa-calendar'></i>                                               <%= article_date(article) %></span>                                               <span class='post-label'><i class='fa fa-tags'></i>                                               <%= article.tags %></span>                                            </div>                                            <div style='clear: both;'></div>                                         </div>                                      </div>                                   </div>                                </div>                               </div>                          </div>                          <% end %>                          <% end %>                       </div>                      </div>                 </div>              </div>              <!-- end main wrapper -->             </div>           <!-- end content-wrapper -->        </div>     </div>     <!-- end outer-wrapper -->  </div>  </div>  

For some reason the definitions which I have set don't seem to have any affect because no matter what the @news is the same at @articles even though I have set what I want specifically using where.

Rails + AngularJS + ActionCabel + Websocket

Posted: 24 Jun 2016 07:49 AM PDT

I am doing rails + angularjs application with real time chat, based on websocket within action cable. I have done all required things about sending and receiving messages through channel connections.

  $scope.moreMessages = function() {      AccountsMessages.query({          conversation_id: $scope.conversationId,          page: $scope.page        },        function(response) {          $scope.page += 1;          $scope.messages = response.messages.concat($scope.messages);        }      )    }      function init() {      $scope.moreMessages();    };    init();      var cable = $cable('/cable');    var channel = cable.subscribe({      channel: 'MessagesChannel',      conversation: $scope.conversationId    }, {      received: function(newMessage) {        if (newMessage) {          $scope.messages.push(newMessage);          $scope.$apply();        }      }    });      $scope.save = function() {      channel.send({        conversation_id: $scope.conversationId,        body: $scope.message.body,        state: 'unread'      });      $scope.message = {};    };  

But right now I am doing read/unread for messages. It is like, one user sends a message to another user. By default, it appears like it is with 'unread' state. But if another user, receiver, views this message, it becomes 'read' or 'viewed'. The problem is, how can I update it like so, that sender dynamically could see mark 'read' on the message state right after that. It is done on server side, and messages are updated while index(query) action is requested by receiver. But how can I do it for sender's vision? Thanks.

Using ldap to connect to ad with devise ruby on rails

Posted: 24 Jun 2016 05:12 AM PDT

Question I am having issues connecting to my Microsoft Active Directory using the devise_ldap_authentication. For some reason I keep getting LDAP search yielded 0 matches when using it with devise and I am 100% certain I am using the correct credentials, so I wrote a test class using 'net/ldap' to see if I could yeild a correct match and presto it works with my test class but, I still can't authenticate with devise_ldap_auth. Any help would be greatly appreciated or help with setting up my config/ldap.yml to match my test class.

Here is my config/ldap.yml

#Environment  development:    host: myldap.mydomain.com    port: 389    attribute: sAMAccountname    base: dc=mydomain, dc=com    admin_user: cn=admin,dc=mydomain,dc=com    admin_password: password    #ssl: false  

Here is my devise.rb

Devise.setup do |config|    # ==> LDAP Configuration    config.ldap_logger = true    # config.ldap_create_user = false    # config.ldap_update_password = true    config.ldap_config = "#{Rails.root}/config/ldap.yml"    # config.ldap_check_group_membership = false    # config.ldap_check_group_membership_without_admin = false    config.ldap_check_attributes = true    #config.ldap_use_admin_to_bind = true    # config.ldap_ad_group_check = false  

this is what I get back when using ldap with devise.

D, [2016-06-24T07:01:30.558440 #42760] DEBUG -- :   LDAP: LDAP dn lookup: sAMAccountName=snow  D, [2016-06-24T07:01:30.558507 #42760] DEBUG -- :   LDAP: LDAP dn lookup: sAMAccountName=snow  D, [2016-06-24T07:01:30.558549 #42760] DEBUG -- :   LDAP: LDAP search for login: sAMAccountName=snow  D, [2016-06-24T07:01:30.558579 #42760] DEBUG -- :   LDAP: LDAP search for login: sAMAccountName=snow  D, [2016-06-24T07:01:30.594029 #42760] DEBUG -- :   LDAP: LDAP search yielded 0 matches  D, [2016-06-24T07:01:30.594099 #42760] DEBUG -- :   LDAP: LDAP search yielded 0 matches  D, [2016-06-24T07:01:30.594146 #42760] DEBUG -- :   LDAP: Authorizing user sAMAccountName=snow,dc=mydomain, dc=com  D, [2016-06-24T07:01:30.594180 #42760] DEBUG -- :   LDAP: Authorizing user sAMAccountName=snow,dc=mydomain, dc=com  D, [2016-06-24T07:01:30.611308 #42760] DEBUG -- :   LDAP: Not authorized because not authenticated.  D, [2016-06-24T07:01:30.611377 #42760] DEBUG -- :   LDAP: Not authorized because not authenticated.  

Here is my test class that works to authenticate with ldap on my microsoft AD

require 'net/ldap' # gem install ruby-net-ldap  module Test    class PutAd      SERVER = 'myldap.mydomain.com'      PORT = 389      BASE = 'DC=mydomain,DC=com'      DOMAIN = 'mydomain.com'        ATTR_SV = {                  :login => :samaccountname,                  :first_name => :givenname,                  :last_name => :sn,                  :email => :mail                }          def self.authenticate(login, pass)        return nil if login.empty? or pass.empty?          conn = Net::LDAP.new :host => SERVER,                             :port => PORT,                             :base => BASE,                             :auth => { :username => "#{login}@#{DOMAIN}",                                        :password => pass,                                        :method => :simple }        if conn.bind and user = conn.search(:filter => "sAMAccountName=#{login}").first          return self.new(user)        else          return nil        end      rescue Net::LDAP::LdapError => e        return nil      end    end   end   

^This will return my account information if it matches if not it will return nil.

Efficient inline editing in Rails

Posted: 24 Jun 2016 05:08 AM PDT

I want to integrate functionality like LinkedIn where, when you're logged in, you can hover over your info on profile page and it will enable you to click on a certain field and you can edit it. And, if it passes validation, that record is edited in the database.

I've seen some jQuery plugins, but I want to stay away of jQuery because of the performance. Are there any Rails solutions or gems that will do this?

Add a new object of a Model without going to /model/new in Rails

Posted: 24 Jun 2016 05:33 AM PDT

Let's say I have my Home page and a Post model. If I want to add a new Post, I go to /posts/new and create a new object of a Post class. That is a standard way.

Can I include, for example, in my Home Page, a + button that will open a small window asking me to type title and content and have the same effect as the standard way ?

How to pass a value from a view to a form Rails 4? [on hold]

Posted: 24 Jun 2016 06:44 AM PDT

I'm learning Ruby on Rails an I would like to get a value form a show view and send to a form new like. I'm in a show animal and I want to send the user through a reproduction button, when he clicks on this the form new reproduction opens and the field mother receives the value of id animal of the show before we came to new.

How can I integrate multiple index Views in one in Rails

Posted: 24 Jun 2016 04:24 AM PDT

Let's say I have 2 models: Post and Friend.

I have to show both of them in Home page. For example, one div will be a grid of all of my friends and the second div will be for all of my posts. Each of them has their own controller, their own model and their own views. Is there a convention for doing things like this?

update a certain column with a set value

Posted: 24 Jun 2016 05:22 AM PDT

I have a set of customers that have credits within my store, i am trying to find their current balance, then adjust it with a new balance, but when doing so i keep getting Amount Invalid but I cannot for the live of work out why this is

CONTROLLER

class Admin::UserDatas::StoreCreditsController < Admin::UserDatas::BaseController    helper_method :customer    def show      @store_credit = customer.store_credit    end      def edit      form_info    end      def update      result = Braintree::Transaction.sale(          :amount => :amount_added,          :customer_id => customer.customer_cim_id,          :options => {              :submit_for_settlement => true          }      )      if result.success?        p 'Transaction Successful'        customer.store_credit.add_credit(:amount_added)        redirect_to admin_user_datas_user_store_credits_url(customer), :notice => "Successfully updated store credit."      else        result.errors.each do |error|          puts error.message          customer.errors.add(:base, error.message)          form_info          render :edit, :notice => error.message        end      end    end      private    def form_info      end      def customer      @customer ||= User.includes(:store_credit).find(params[:user_id])    end      def amount_added      params[:amount_to_add].to_f    end    end  

METHODS

def remove_credit(amount_to_remove)      credit_amount = "#{self.amount} - #{amount_to_remove.to_f.round(2)}"      self.update(amount: credit_amount)    end      def add_credit(amount_to_add)      credit_amount = "#{self.amount} + #{amount_to_add.to_f.round(2)}"      self.update(amount: credit_amount)    end  

FORM PARTIAL

%ul.admin-standard_form.prepend-8{:id => ""}    %li.field      = label :amount_to_add, 'Amount to Add'      = text_field_tag :amount_to_add  

EDIT TEMPLATE

%h3    Change #{customer.name} Store Credit  %ul    %li      %label Current Amount:      = number_to_currency customer.store_credit_amount  = form_for customer, :url => admin_user_datas_user_store_credits_path( customer ) do |f|    = render :partial => 'form', :locals => {:f => f}    .actions= f.submit 'Update' , :class => 'button'  

ERRORS

Started PATCH "/en/admin/user_datas/users/1/store_credits" for 127.0.0.1 at 2016-06-24 21:56:08 +1000  Processing by Admin::UserDatas::StoreCreditsController#update as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "amount_to_add"=>"200", "commit"=>"Update", "locale"=>"en", "user_id"=>"1"}    User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."remember_token" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["remember_token", "cfe807bd1caa3763df52dcb18de8c9d4f350b933"]]    User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]    StoreCredit Load (0.5ms)  SELECT "store_credits".* FROM "store_credits" WHERE "store_credits"."user_id" IN (1)  I, [2016-06-24T21:56:09.418606 #8775]  INFO -- : [Braintree] [24/Jun/2016 11:56:09 UTC] POST /merchants/XXXX/transactions 422  Amount is an invalid format.    Rendered admin/user_datas/store_credits/_form.html.haml (0.7ms)    Rendered admin/user_datas/store_credits/edit.html.haml within layouts/superman (4.0ms)    Rendered shared/_meta_data.html.haml (4.6ms)    Rendered admin/shared/_side_menu.html.haml (2.8ms)  Completed 200 OK in 1085ms (Views: 47.2ms | ActiveRecord: 1.3ms)  

MORE ERRORS

Started PATCH "/en/admin/user_datas/users/1/store_credits" for 127.0.0.1 at 2016-06-24 22:20:46 +1000  Processing by Admin::UserDatas::StoreCreditsController#update as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "amount_to_add"=>"20", "commit"=>"Update", "locale"=>"en", "user_id"=>"1"}    User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."remember_token" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["remember_token", "cfe807bd1caa3763df52dcb18de8c9d4f350b933"]]    User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]    StoreCredit Load (0.5ms)  SELECT "store_credits".* FROM "store_credits" WHERE "store_credits"."user_id" IN (1)  I, [2016-06-24T22:20:50.681897 #8775]  INFO -- : [Braintree] [24/Jun/2016 12:20:50 UTC] POST /merchants/mbmb637xwpzgxbrd/transactions 201  "Transaction Successful"     (0.2ms)  BEGIN     (0.2ms)  ROLLBACK  Redirected to http://0.0.0.0:3000/en  Completed 302 Found in 3848ms (ActiveRecord: 1.6ms)  

Get day numbers of a week number

Posted: 24 Jun 2016 04:40 AM PDT

In my application I store activities with a day_number ranging from 1 to 31 and a number of hours. Any activity belongs to a timesheet which contains a month and year.

Now I want to have an overview with all the weeks in a year and with the total number of activity hours in that week. I determine the weeks of a month with:

first_week = Date.new(timesheet.year,timesheet.month,1).strftime("%U").to_i  last_week = Date.new(timesheet.year,timesheet.month,1).end_of_month.strftime("%U").to_i  weeknrs = (first_week..last_week).to_a  weeknrs.each do |weeknr|    # Do something  end  

How can I determine the day numbers belonging to a specific week?

" I want to customise my dashboard page in ActiveAdmin, But I am getting this error "Uninitialised constant Dashboards"

Posted: 24 Jun 2016 04:45 AM PDT

This is my dashboard ruby file . I want to know what is causing the error ""Uninitialised constant Dashboards" which is in line 1st.I am using ruby on rails 4 on windows.

ActiveAdmin ::Dashboards.build do      section "Recent Posts" do          table_for Post.order("id.desc").limit(15) do              column :id              colunm :"Post Title",:title do |post|              link_to post.title,(:admin.post)              end              column :category,:sortable => :category              column :created_at          end          strong (link_to "Show all Posts")      end      end  

Rails Presenter Pattern - Yield Duplicates HTML Code

Posted: 24 Jun 2016 04:03 AM PDT

I'm doing a bit of view logic refactoring, following the presenter pattern Ryan Bates brilliantly tutors in his #287 Presenters from Scratch Railscast- which can be seen here: http://railscasts.com/episodes/287-presenters-from-scratch

I have a scenario where a view file HTML logic is wrapped in a few ugly if statements limiting access to the page, based on certain attributes of the model. For Example:

<% if @user.my_friend? %>      <% if @user.not_apart_of_group? %>          <div> Sorry, you're not apart of your friends group! </div>      <% else %>          <% if @user.group_admin? %>              /* html code to edit group, with lots of horrid logic */          <% else %>              <div> Sorry, you're not an admin of your friends group! </div>          <% end %>      <% end %>  <% else %>      <% if @user.not_apart_of_group? %>          <div> Sorry, you're not apart of this public group! </div>      <% else %>          <% if @user.group_admin? %>              /* html code to edit group, with lots of horrid logic */          <% else %>              <div> Sorry, you're not an admin of this public group! </div>          <% end %>      <% end %>  <% end %>  

My above example mimics a scenario where the view page is used to render a group admin page for both friend groups and public group, but the one served depends on some logic in the controller. As you can see, it's a horrible mess of nested if statements in the view file, so I began to move it a presenter ruby class that contains methods that does the job of the if statements. For example, in the view file, I call the method as a block and pass the html code that I want to render, if the @user object meets all the requirements of the page:

<% present @user do |user| %>      <%= user.render_group_admin do %>          /* html code */      <% end %>  <% end %>  

In my presenter class, I have the method render_group_admin which yields the html code if the @user object meets of the criteria, or returns the content_tag with one of the above simple splash screens- this again depends on what criteria the object doesn't meet:

class User::UserPresenter < BasePresenter      presents :user        def render_group_admin          if user.is_friend              h.content_tag :div, class:"blah blah blah" do                   "Sorry, you're not apart of your friends group!"              end          elsif ...              #various condition checks           else              yield #meets all conditions, so we'll yield the html          end      end  end  

This worked great and allowed me to completely remove the nested if statements from the view file and put them in a Ruby Class that does the job for me and allows me to write RSpec test that test the logic directly (and avoid that horrible capybara for front end testing).

Well, apart from one problem....

When I ran the code for the first time, I found that my presenter method was rendering (or yielding) the html code passed to it, twice.

I did a bit a tinkering and found that adding return "" under the yield, like so:

class User::UserPresenter < BasePresenter      presents :user        def render_group_admin          if user.is_friend              h.content_tag :div, class:"blah blah blah" do                   "Sorry, you're not apart of your friends group!"              end          elsif ...              #various condition checks           else              yield #meets all conditions, so we'll yield the html              return ""          end      end  end  

This sorted the issue, well, I guess renders my html code + the blank string- but aesthetically, achieved what I wanted. Albiet, in a hacky looking way.

My questions really are:

  1. why does yield render my html code twice, when called in a helper-like method from the view file?

  2. Is there a way to stop this duplication behavior in a better way than simply putting the line return "" under it?

Thanks in advance guys and gals,

Anything wrong with this plan for my model associations

Posted: 24 Jun 2016 05:28 AM PDT

I'm creating an app that allows users to take multiple choice quizzes that I create.

There's a Quiz model, a Question Model, and an Answer model. The Quiz model has_many questions which has_many answers (and they all belongs_to the model intuitively above them). answers will have a correct_answer boolean attribute that indicates ONE of the answers to be the correct answer. (and they all belongs_to the model intuitively above them). This is to create the quiz.

To provide support for user input once the quiz has already been created, I want to define two other models: SubmittedAnswer and SubmittedSurvey. SubmittedSurvey belongs_to User, and also belongs_to Survey (both of which has_many submittedsurveys). SubmittedSurvey also has_many submittedanswers.

So when you visit the page that displays the quiz, it allows user input which submits data that sets submittedanswers. Then, since submittedsurvey belongs_to survey, I can compare submittedanswers to the answers themselves and grade the quiz. Is this reasonable or should I do it some other way?

RoR tutorial (Michael Hartl) URI::InvalidURIError

Posted: 24 Jun 2016 06:24 AM PDT

I am following the RoR tutorial by Michael Hartl. Currently on chapter 3. My problem is that I don't get the view I should've seen at https://www.railstutorial.org/book/static_pages#fig-raw_home_view.

Instead I'm seeing an

enter image description here

The URL I'm trying to enter is: "localhost:3000/static_pages/help". The application.html.erb looks like this:

<!DOCTYPE html>  <html>  <head>    <title>SampleApp</title>    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>    <%= csrf_meta_tags %>  </head>  <body>    <%= yield %>    </body>  </html>  

I'm still a rookie so really don't know what to do.

How to do configure sabre rest api for air instaflight search api and other related api?

Posted: 24 Jun 2016 03:40 AM PDT

I have create account in sabre dev api. How to get instaflight data? I am using ruby on rails. I have get client secret and key. How to use sabre dev REST api services.

No comments:

Post a Comment