Sunday, October 23, 2016

ActiveRecord's query misbehavior for outer joins? | Fixed issues

ActiveRecord's query misbehavior for outer joins? | Fixed issues


ActiveRecord's query misbehavior for outer joins?

Posted: 23 Oct 2016 07:33 AM PDT

Lets have two ActiveRecord models Product and Promotion

Building query with outer join and alias for joined table column produces following invalid SQL:

Product.distinct.includes(:promotion).select('promotions.advertised as featured').  references(:promotion).order('featured').limit(10).to_sql    SELECT  DISTINCT "products"."id", featured AS alias_0 FROM "products"                                    ^^^^^^^^^^^^^^^^^^^   LEFT OUTER JOIN "promotions" ON "promotions"."product_id" = "products"."id"  ORDER BY featured LIMIT 10  

Execution results in database error: ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "featured" does not exist. As expected, because featured is alias to promotions.advertised column, not defined in table products.

As you can see, ActiveRecord injects invalid "featured AS alias_0" expression into select. In addition, all columns of products table, except id, are omitted.

Above misbehavior is related to simultaneous use of order AND limit methods. When any of them is omitted, produced SQL becomes correct. For example just single removal of limit produces right query:

Product.distinct.includes(:promotion).select(promotions.advertised as featured').  references(:promotion).order('featured').to_sql    SELECT  DISTINCT promotions.advertised as featured, "products"."id" AS t0_r0, "products"."name" AS t0_r1, … FROM "products"  LEFT OUTER JOIN "promotions" ON "promotions"."product_id" = "products"."id"  ORDER BY featured  

Can anybody explain this behaviour ?

Candidate for a bugreport or am I missing something ?

tested with ActiveRecord ver. 4.2.7.1

JBuilder/Rails 5: return simple string instead of json object

Posted: 23 Oct 2016 06:33 AM PDT

using jbuilder and rails 5, is it possible to transform a model object into a simple string, for example with this object:

tag = {    tag: 'sometag',    created_by: 1  }  

using _tag.json.jbuilder to serialize the model to:

'sometag'  

instead of:

{    "tag": "sometag",    "created_by": 1  }  

the idea is that the index action of my controller returns an array of strings instead of an array of objects

['a','b','c']  

not

[{name:'a'},{name:'b'},{name:'c'}]  

The scaffolded contents of _tag.json.jbuilder is

json.extract! tag, :name, :created_by  

I tried

tag.name  

but the result is empty. How to do this with jbuilder?

Why it's useful to create RVM gemset for rails project

Posted: 23 Oct 2016 06:29 AM PDT

It's recommended to create a separate RVM gemset for each rails project. But I don't understand, why it's useful. Are there only aesthetics reasons? Because it is possible to install multiple gem versions globally and then write a version in Gemfile in case I need a specific version of a gem.

redirect rails id show method to rails permalink

Posted: 23 Oct 2016 05:08 AM PDT

I have the has_permalink gem set up and working fine.

However, google is crawling my website with looking for events with ids, not the permalink.

This is what i currently have:

@event = Event.find_by_permalink(params[:id])  

However when someone types in an ID e.g. /events/000001 then @event is blank.

The solution I came up with is this:

@event = Event.find_by_permalink(params[:id])  if @event.blank?    @event = Event.find_by_id(params[:id])  end  

But I would rather have the website still show the friendly URL link in the URL rather than the ID of the event.

Any ideas how I would approach this?

Thanks Sam

Table showing the result of queries using rails

Posted: 23 Oct 2016 07:24 AM PDT

Here is my problem. I have a model called Visit (which belongs to Visitor model):

create_table "visits", force: true do |t|      t.datetime "created_at",                         null: false      t.datetime "updated_at",                         null: false      t.date     "start"      t.date     "end"      t.integer  "idVisit"      t.integer  "employee_id"      t.integer  "visitor_id"      t.string   "status",      default: "Confirmed"    end  

I have a table like this (name, last name and serial number are visitor's fields):

Name, Last name, Serial number, From, To

Now I have four buttons: Current visits, Confirmed and about to start visits, Terminated visits, Visits to be approved

I need that, clicking on these buttons, the table shows the result of queries. For example, clicking on Terminated visits the table will show all the visits having end < Date.today, clicking on Current Visits the table will show all the visits having start <= Date.today && end >= Date.today and so on and so forth.

In addition, Current visits button should be considered selected as default.

I don't have any idea about this kind of implementations being a newbie at Ruby on Rails and I really hope you can help me.

Thank you in advance!

EDIT:

    <div class="jumbotron3 text-center">          <div class="row">          <h1>Guests Visits</h1>          <hr>          <%=render :partial =>"layouts/sidebar"%>          <div class="panel3">              <div class="panel-body">                    <% if logged_in? %>                      <%=render :partial =>"shared/error_messages"%>                        <% if @employee.visits.any?%>                      <br><br>                      <input type="button" id='current' value='Current Visits'>                      <input type="button" id='confirmed' value='Confirmed Visits'>                      <input type="button" id='terminated' value='Terminated visits'>                      <input type="button" id='pending' value='Pending Visits'>                      <br><br>                        <table class="table2 display" id="visit">                          <thead>                          <tr>                            <th>Name</th>                            <th>Last name</th>                            <th>Serial number</th>                            <th>From</th>                            <th>To</th>                          </tr>                          </thead>                          <%= render @visits %>                      </table>                      <br><br>                      <% end %>                 <% end %>         </div>  </div>  

My main problem is the following: I need to fill the table with visit.visitor.name, visit.visitor.lastname, visit.visitor.serialnumber, visit.start, visit.end (by default I need to show the results of button current).

When I click on one button, the table should show just the entries which respect the condition associated the clicked button. Ex: if I click on terminated, the table should show the entries having end < Date.today.

Rails 5 missing template that was added to lookup

Posted: 23 Oct 2016 06:17 AM PDT

I have added into application.rb string

config.paths['app/views'] << 'app/views/cabinet'

and created a view 'app/views/cabinet/index.html.slim'.

But when I go to route localhost:3000/manager/pages (It uses layout manager if it make sence), Rails gives the error

Manager::PagesController#index is missing a template for this request format and variant.

What I'm doing wrong?

Heroku run rake db:migrate error when trying to deploy

Posted: 23 Oct 2016 06:36 AM PDT

I'm trying to deploy my Rails app on Heroku. It was working up until I tried to run heroku run rake db:migrate.

I'm getting this error:

rake aborted!  StandardError: An error has occurred, this and all later migrations canceled:    PG::UndefinedColumn: ERROR:  column "admin" of relation "users" does not exist  : ALTER TABLE "users" DROP "admin"  

I've been trying to fix this for a couple hours. Any help would be greatly appreciated!

Added Column Not accessible in next migration file

Posted: 23 Oct 2016 05:11 AM PDT

I have added a column to my table via a migration, but I am not able to access the added column in the subsequent migration file.

When I execute rake db:migrate the migration aborts, but when I execute it again the migration succeeds, not sure what I am doing wrong. Any help would be appreciated. Thanks.

below is the code where i am adding column

**

class AddIsDispatchToUsers < ActiveRecord::Migration    def change      add_column :users, :is_dispatch, :boolean, :default=>false    end  end  

**

Now, when i try to access the column in next migration file it fails.

The subsequent migration file has the code below

service_member = Member.create(:is_dispatch=>true)

And Here is the error that it produces

unknown attribute: is_dispatch/Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:1764:in `block in assign_attributes'  /Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:1758:in `each'  /Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:1758:in `assign_attributes'  /Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:1578:in `initialize'  /Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:508:in `new'  /Users//.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/base.rb:508:in `create'  /Users//Desktop/RailsDevelopement//db/migrate/20161003121452_add_dispatch_services.rb:11:in `up'  

Dynamically mount Carrierwave uploader on serialized field

Posted: 23 Oct 2016 02:24 AM PDT

I'm creating this app where users are able to dynamically add custom fields (TemplateField) to a template (Template) and use that template on a page (Page).

The custom fields can have type text or image, and have custom naming. A user can for instance create at field named Profile picture of type image to their template.

I can't however figure out how to dynamically mount a CarrierWave uploader to fields of type image, when everything is saved to an hstore attribute (properties) on the page model.

Any help is much appreciated!

class Template < ActiveRecord::Base    has_many :template_fields    has_many :pages  end    class Page < ActiveRecord::Base    belongs_to :template      store_accessor :properties  end    class TemplateField < ActiveRecord::Base    belongs_to :template  end  

Not able to connect mongodb with Rails container using Docker compose

Posted: 23 Oct 2016 01:38 AM PDT

Getting this error when inserting values in Model through rails console .

"Mongo::Error::NoServerAvailable: No server is available matching preference: # using server_selection_timeout=30 and local_threshold= 0.015 "

Both containers are running fine, but Rails not able to connect mongodb .

My docker-compose.yml file contents are:

 version: '2'    services:    mongo:      image: mongo:3.0      command: mongod --smallfiles --quiet      environment:        - RAILS_ENV=production        - RACK_ENV=production      ports:        - "27017:27017"      app:      depends_on:        - 'mongo'        # - 'redis'      build: .      ports:        - '3000:3000'      volumes:        - '.:/app'      command: rails s -b '0.0.0.0'      env_file:        - '.env'    volumes:    mongo:  

My Dockerfile :

FROM ruby:2.3.0  RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs    ENV APP_HOME /app    RUN mkdir $APP_HOME    WORKDIR $APP_HOME      ADD Gemfile* $APP_HOME/   RUN bundle install      ADD . $APP_HOME  

How to properly load lib modules and classes in Rails 5 app

Posted: 23 Oct 2016 01:38 AM PDT

How do I include a 'lib/' class or module in my models, Grape API and tests? For example, I have a class:

ROOT/lib/links/link.rb

module Links    class Links::Link      ...    end  end  

And I want to include that class in my User model (app/models/user.rb), User Grape API (app/api/v1/users.rb), and testing suites (test/models/user_test.rb and test/api/v1/users/users_links_test.rb)

I've tried adding this to my config/application.rb:

config.autoload_paths += Dir["#{Rails.root}/lib/**"]

but it doesn't work. What am I missing? How do I include lib files and how should I be calling those classes?

Model name and path after routing in Rails

Posted: 23 Oct 2016 01:26 AM PDT

Here's my routing

resources :users do    resources :tasks    end  

I have an error in the page new (form rendering)

That was before routing add and everything works great

= simple_form_for(@task) do |f|  

Then I change it to

= simple_form_for(@user_task) do |f|  

And got at error: undefined method `model_name' How should I fix it?

Ruby on Rails, taking data from Graphql and posting on it to Facebook-messenger

Posted: 23 Oct 2016 12:22 AM PDT

  $message_text = message.text    module STAPI      HTTP = GraphQL::Client::HTTP.new("API_ADDRESS")      Schema = GraphQL::Client.load_schema(HTTP)      Client = GraphQL::Client.new(schema: Schema,execute: HTTP)    end      module Sticker      Query = STAPI::Client.parse <<-'GRAPHQL'        {          stickers(query: "#{$message_text}", first: 21, after: "") {            edges {              node {                fileUrl(fullWatermarked: true)              }            }          }        }      GRAPHQL    end      result = STAPI::Client.query(Sticker::Query)  

First of all this is an messenger bot and with this messenger bot i am taking users input and i am searching the input in our database then i post something related with the input.

So, in the code i can't search beacuse, in my opinion query: "#{$message_text}" is broken.

I take users input with message.text . This input comes like this 'Hello' (with '). But i need to give query: "#{$message_text}" part like this "Hello"(with "). how can i give messenger.text to query part like this "Hello"

Different versions of the index page for ActiveAdmin

Posted: 23 Oct 2016 12:20 AM PDT

I'd like to have two different index pages for my model, i.e. /admin/posts/ will be the default index page and /admin/posts/index/special will be another version. Perhaps I'm missing something obvious, but I haven't found an explanation in the official docs.

How to define let! with mutliple objects in Rspec test?

Posted: 23 Oct 2016 02:49 AM PDT

I'm practicing my Rails tests and right now I don't know how to solve this issue: How to define multiple objects using let! method. It returns normal array, not ActiveRecord relation. I guess that they should be both ActiveRelation relation type to be able to compare.

require 'rails_helper'    RSpec.describe PostsController do      let!(:posts) do         [Post.create(title: "Title 1", body: "Body 1"), Post.create(title: "Title 2", body: "Body 2")]    end      describe "posts" do      it "assigns @posts" do          get :index        expect(assigns(:posts)).to eq([posts])      end    end    end  

After running tests:

PostsController    posts      assigns @posts (FAILED - 1)    Failures:      1) PostsController posts assigns @posts       Failure/Error: expect(assigns(:posts)).to eq([posts])           expected: [[#<Post id: 1, title: "Title 1", body: "Body 1", created_at: "2016-10-23 05:40:39", updated_at: "201...: "Title 2", body: "Body 2", created_at: "2016-10-23 05:40:39", updated_at: "2016-10-23 05:40:39">]]              got: #<ActiveRecord::Relation [#<Post id: 1, title: "Title 1", body: "Body 1", created_at: "2016-10-23 05:...: "Title 2", body: "Body 2", created_at: "2016-10-23 05:40:39", updated_at: "2016-10-23 05:40:39">]>           (compared using ==)           Diff:         @@ -1,3 +1,13 @@         -[[#<Post id: 1, title: "Title 1", body: "Body 1", created_at: "2016-10-23 05:40:39", updated_at: "2016-10-23 05:40:39">,         -  #<Post id: 2, title: "Title 2", body: "Body 2", created_at: "2016-10-23 05:40:39", updated_at: "2016-10-23 05:40:39">]]         +[#<Post:0x000000063ef570         +  id: 1,         +  title: "Title 1",         +  body: "Body 1",         +  created_at: Sun, 23 Oct 2016 05:40:39 UTC +00:00,         +  updated_at: Sun, 23 Oct 2016 05:40:39 UTC +00:00>,         + #<Post:0x000000063ef228         +  id: 2,         +  title: "Title 2",         +  body: "Body 2",         +  created_at: Sun, 23 Oct 2016 05:40:39 UTC +00:00,         +  updated_at: Sun, 23 Oct 2016 05:40:39 UTC +00:00>]         # ./spec/controllers/posts_controller_spec.rb:13:in `block (3 levels) in <top (required)>'    Finished in 0.43037 seconds (files took 2.4 seconds to load)  1 example, 1 failure    Failed examples:    rspec ./spec/controllers/posts_controller_spec.rb:10 # PostsController posts assigns @posts  

How to get access token and refresh token from google api?

Posted: 22 Oct 2016 10:07 PM PDT

has_attached_file :project,    styles: { small: '48x48', medium: '128x128' },    storage: :google_drive,    google_drive_credentials: "#{Rails.root}/config/google_drive.yml",    google_drive_options: {      path: proc { |style| "#{style}_#{id}_#{photo.original_filename}" }    }      

Using

gem 'paperclip-googledrive'  

I added google_drive.yml file for credential. when I download credential file from google api I get following things

  1. Client ID
  2. Client Secret

Now I also need

  1. Access Token
  2. Refresh Token

So How can I get this two token from google ?

Can you please help me to how can I find this or How can i generate this?

Displaying and Creating multiple entities rails

Posted: 22 Oct 2016 10:03 PM PDT

Hey guys im learning rails and as an assignment we have to do a site where people can bet on sport matches. Each match has two teams and three dividends (local win, visitor win or draw) that determine the users profit for each bet.

These bets alone have no value because they go on to a ticket associated with the user and the amount and where the total profit is calculated. The ticket consists of up to three bets.

Right now i have all the logic and views of the Matches but im trying to do the ticket one and im having some trouble.

I already display a list of matches to the user like this: Match list

From there i would like it if the user could click on the dividend number to select the match and the result desired and that would make that selection one of the three possible bets. For instance, if the user clicks on the draw dividend that would load a bet with that dividend for those two teams and a draw result.

Once the user clicks on a dividend i want to dynamically load a table showing the current bet selected and a "submit" button that from those bets generates the ticket and persists them all to the database, how can i do it in a simple way?

Thank You!

Update rails with amazon cloudfront and test rails

Posted: 22 Oct 2016 09:15 PM PDT

I am new to rails and also to amazon cloudfront.

I went through the link below to create amazon distribution

https://devcenter.heroku.com/articles/using-amazon-cloudfront-cdn  

I created an amazon distribution group using DEV server origin domain name as

assets.mainLine.myhealth.com  

Distribution domain name is

q0iumhgr1r387.cloudfront.net  

I am working locally on application

 http://myhealth.com:3000/  

This is the css rails application serving

https://abcd.mainline.stagingiqhealth.com/assets/abcd-2a7a5cc56c42fe6e1f84929847cbf7ff8583300451ca00cd20e98ca1ea74b.css  

How can i test the css above before updating rails code?

How can i update the rails production.rb for cloudfront distribution?

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.     config.action_controller.asset_host = "http://assets.example.com"  

We have dev/stage/prod servers so in order to test on dev server do i need to update development.rb in cofig/environments?

Also can i test application locally for this or do i need dev server?

Thanks

How can I prepare my rails app for production?

Posted: 22 Oct 2016 08:02 PM PDT

I've built a marketplace application using Rails, Devise, Heroku, and Stripe Connect.

I want to launch the application in about 30 days. I have never actually launched an app that will be available to customers and has money involved. I'm kind of hazy in regards to what I need to do from here out to make sure the application will work as intended for the customers.

I've read Basecamps Rework book which motivated me to launch sooner than trying to perfect it and have made the app as agile as possible as a result. I can't say I'm much of a programmer as I learned rails and programming in my spare time.

If anyone has any experience in managing a rails app for live production please give me tips on things you wish you knew before. Thank you!

MySQL/Rails - Mysql2::Error (Access denied for user 'rails_user'@'localhost' to database 'simple_cms_development'):

Posted: 22 Oct 2016 07:56 PM PDT

I'm new to both MySQL and Rails. I'm going through a course on Lynda (Ruby on Rails 5) and I ran into a hiccup. After creating a database it's having me start up MySQL and Puma. I attempt to access localhost:3000 however I get the following error:

Mysql2::Error (Access denied for user 'rails_user'@'localhost' to database 'simple_cms_development'):  

It seems like everything is working properly, both MySQL and Puma start:

Johns-MBP:simple_cms johnerickson$ mysql.server start  Starting MySQL  SUCCESS!  Johns-MBP:simple_cms johnerickson$ rails s  => Booting Puma  => Rails 5.0.0.1 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  Puma starting in single mode...  * Version 3.6.0 (ruby 2.3.0-p0), codename: Sleepy Sunday Serenity  * Min threads: 5, max threads: 5  * Environment: development  * Listening on tcp://localhost:3000  * List item  

Below is my database.yml file:

default: &default    adapter: mysql2    encoding: utf8    pool: 5    username: rails_user    password: ***The password works***    host: localhost    development:    <<: *default    database: simple_cms_development  

I looked through Stack Overflow and see others have had similar issues, however it seemed to be a password issue, which I'm not having. Any help will be greatly appreciated.

Form submission within render partial is showing errors for all forms on all objects

Posted: 22 Oct 2016 07:20 PM PDT

To clarify my title, my portfolio/show file looks like

<p>    <strong>Name:</strong>    <%= @portfolio.name %>  </p>    <%= content_tag :canvas, "", id: "positions_chart", width: "300", height: "300", data: {positions: @positions } %>      <h1>Positions</h1>  <div class = 'table'>  <table>    <thead>      <tr>        <th>Name</th>        <th>Quantity</th>        <th>Stock</th>        <th colspan="3"></th>      </tr>    </thead>  <tbody id = "positions">    <%= render @positions %>  </tbody>  </table>  </div>    <h3>New Position</h3>    <%= render 'positions/form' %>    <%= link_to 'Edit', edit_portfolio_path(@portfolio) %> |  <%= link_to 'Back', portfolios_path %>  

The file that is rendering in line <%= render @positions %> is my _position.html.erb file.

<tr>    <td class="col-md-1"><%= position.name %></td>    <td class="col-md-1"><%= position.quantity %></td>    <td class="col-md-1"><%= position.ticker %></td>    <td>      <%= form_for [@portfolio, position, @movement] do |f| %>        <div id = "movement-errors">          <% if @movement.errors.any? %>            <%= render 'shared/error_messages', object: @movement %>          <% end %>        </div>          <div class="field">          <%= f.label :quantity, 'Buy' %>          <%= f.number_field :quantity, class: 'form-control' %>        </div>        <div class="actions">          <%= f.submit class: 'btn btn-primary' %>        </div>      <% end %>    </td>    <td>      <%= form_for [@portfolio, position, @movement], url: sell_portfolio_position_movements_path(@portfolio, position, @movement), method: :post do |f| %>        <div id = "movement-errors">          <% if @movement.errors.any? %>            <%= render 'shared/error_messages', object: @movement %>          <% end %>        </div>          <div class="field">          <%= f.label :quantity, 'Sell' %>          <%= f.number_field :quantity, class: 'form-control' %>        </div>        <div class="actions">          <%= f.submit class: 'btn btn-success' %>        </div>      <% end %>    </td>  </tr>  

When I submit a number to buy or sell shares, the post request goes through and a movement is created. The issue I'm having is that I want to show an error message when a person submits nothing ensuring that a movement always has an integer value. My first error when dealing with this problem was when I submitted a nil value, I would get an error saying @partials within the render line was not defined. So I defined the variable in movements_controller. When I submit a nil value now, 2 things happen: 1) the post goes through and a movement is made with a quantity of nil, and 2) All of the buy/sell forms on all the position objects show me the error saying quantity should be present.

My movement class is defined

class Movement < ApplicationRecord    belongs_to :position    validates :quantity,              presence: true,              numericality: true  

My movement create method is defined as

def create    @movement = @position.movements.build(movement_params)      @movement.update_price_and_date    @movement.trade ='buy'      respond_to do |format|      if @movement.save        @position.update_attribute(:quantity, (@movement.quantity + @position.quantity))        format.html { redirect_to @portfolio, notice: "#{params[:movement][:quantity]} share(s) successfully bought." }        format.js      else        format.html { render template: 'portfolios/show' }        format.json { render json: @movement.errors, status: :unprocessable_entity }        format.js      end    end  end  

and the sell action is defined as

def sell    @movement = @position.movements.build(movement_params)    @movement.trade ='sell'      respond_to do |format|      if @position.sell(params[:movement][:quantity].to_i)        @position.update_attribute(:quantity, (@position.quantity - @movement.quantity))        format.html { redirect_to @portfolio, notice: "You sold #{params[:movement][:quantity]} share(s)." }        format.json { render :show, status: :created, location: @position }      else        format.html { render 'portfolios/show' }        format.json { render json: @position.errors, status: :unprocessable_entity }        format.js      end    end  end  

Rails 5 display number of results when grouped

Posted: 22 Oct 2016 08:18 PM PDT

I'm building an app using will paginate and ransack.

My controller:

 def index        @q = Stockdiary.all.ransack(params[:q])      @stockdiaries =   @q.result.joins(:product).group(:PRODUCT).select("SUM(UNITS) AS UNITS, SUM(PRICE) AS PRICE").paginate(:page => params[:page], :per_page => 30)      end  

Then in my view I have this to show the number of entries found:

  <div> <%= pluralize(@stockdiaries.size, 'stockdiary') %> found</div>  

But as I am applying group, it shows

{"1"=>6, "103"=>2, "104"=>1, "106"=>2, "115"=>2, "116"=>1, "118"=>1, "122"=>1, "124"=>2, "13"=>6, "130"=>1, "133"=>3, "137"=>2, "138"=>2, "14"=>2, "140"=>1, "142"=>1, "144"=>1, "145"=>1, "146"=>2, "148"=>3, "149"=>1, "151"=>3, "152"=>3, "154"=>4, "16"=>4, "160"=>1, "161"=>1, "163"=>2, "166"=>1, "170"=>2, "174"=>1, "18"=>2, "19"=>1, "2"=>1, "25"=>3, "27"=>2, "29"=>1, "31"=>1, "33"=>1, "34"=>1, "43"=>2, "49"=>2, "56"=>1, "70"=>6, "73"=>4, "83"=>1, "9"=>2, "9e249a40-82d3-499f-a2b8-9f8613ecfe81"=>2, "bcea85d5-2596-4e41-8245-e520bc2b07a8"=>2} stockdiaries found  

which shows thew number of entries for each product (as it's grouped by product). Obviously I need to show just the total entries, not for each product.

How to fix this?

Skipping Active Record breaks Rails Generator

Posted: 23 Oct 2016 02:33 AM PDT

I created a new Rails project with the -O --api flags turned on, and rails g model is now broken for me: it does nothing and simply says "running via Spring preloader" (its not a Spring bug as I've tried removing Spring) and returns.

After that, I created a new project (exactly the same, just without -O), and rails g model worked fine. Is it that skipping AR breaks generators? If so, how shall I avoid?

I'm using Ruby 2.3.1 and Rails 5.0.0.1 on Ubuntu Linux 16.04 LTS.

flash[:notice] is throwing error when I use Ruby 1.9 with Rails 2.3.4

Posted: 22 Oct 2016 03:29 PM PDT

The Post pages I just generated using the scaffolding but they are not working When I try to access the New post page it give me the error.

Here is My layout code

    <p style="color: green"><%= flash[:message] %></p>      <%= yield %>  

Error that I get when i try to access the page

    Processing PostsController#new (for 127.0.0.1 at 2016-10-23 02:45:19) [GET]      Rendering template within layouts/posts      Rendering posts/new     ActionView::TemplateError (undefined method `^' for "4":String) on   line #12 of app/views/layouts/posts.html.erb:      9: </head>     10: <body>     11:      12:p style="color: green"><%= flash[:message] %></p>     13:        14: <%= yield %>     15:     app/views/layouts/posts.html.erb:12  app/controllers/posts_controller.rb:29:in `new'  <internal:prelude>:10:in `synchronize'  /home/atta/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'  /home/atta/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'  /home/atta/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'  

Here is the gem list that I am using with ruby 1.9

    actionmailer (2.3.4)      actionpack (2.3.4)      activerecord (2.3.4)      activeresource (2.3.4)      activesupport (2.3.4)      bigdecimal (1.1.0)      bundler-unload (1.0.2)      executable-hooks (1.3.2)      gem-wrappers (1.2.7)      io-console (0.3)      json (1.5.5)      minitest (2.5.1)      rack (1.0.1)      rails (2.3.4)      rake (0.9.2.2)      rdoc (3.9.5)      rubygems-bundler (1.4.4)      rubygems-update (1.8.25)      rvm (1.11.3.9)      sqlite3 (1.3.12)      sqlite3-ruby (1.3.3)  

Note: I also downgraded my RubyGems to 1.8.25 as newer was not working with db:create rake command

ElasticSearch: Altering indexed version of text

Posted: 22 Oct 2016 03:00 PM PDT

Before the text in a field is indexed, I want to run code on it to transform it, basically what's going on here https://www.elastic.co/guide/en/elasticsearch/reference/master/gsub-processor.html (but that feature isn't out yet).

For example, I want to be able to transform all . in a field into - for the indexed version.

Any advice? Doing this in elasticsearch-rails.

Split youtube url rails

Posted: 22 Oct 2016 03:18 PM PDT

I m trying to parse youtube url. At this time my code is ok with standard youtube url.

https://www.youtube.com/watch?v=tYMFIIVOHyo  

But don't work with list or youtu.be like this

https://www.youtube.com/watch?v=tYMFIIVOHyo&list=UUH3V-b6weBfTrDuyJgFioOw  https://youtu.be/tYMFIIVOHyo?list=UUH3V-b6weBfTrDuyJgFioOw  https://youtu.be/tYMFIIVOHyo  

My code is

module CampingsHelper    def embed(youtube_url)     youtube_id = youtube_url.split("=").last     content_tag(:iframe, nil, src: "//www.youtube.com/embed/#{youtube_id}")   end  

How I can fix this ?

By the way I want to show an alert if url isn't from youtube.

Rails root test

Posted: 22 Oct 2016 03:19 PM PDT

I am a beginner and am trying to test whether the following code maps to the "home page":

Rails.application.routes.draw do    root 'static_pages#home'  end  

what should I replace the first and second "FILL_IN" with in the block below?

test "should get root" do      get FILL_IN      assert_response FILL_IN  end  

Would appreciate your help!

In Ruby, What exactly is the difference between RVM, Bundler and Rake?

Posted: 22 Oct 2016 03:20 PM PDT

I know RVM stands for Ruby Version Manager, and that it helps you manage the versions of ruby across projects.

But when running commands, programs or tasks some times you use rake and sometimes you use bundle.

Big discrepancy in ruby Time arithmetic used with active support Time extensions

Posted: 22 Oct 2016 02:42 PM PDT

This code should not have, to my understanding, produce different results between third and second examples.

0> Time.utc(1999, 12, 29) - Time.utc(1999, 12, 29)  => 0.0    0> Time.utc(1999, 12, 29) + 1.month - Time.utc(1999, 12, 29)  => 2678400.0    0> 1.month.to_i  => 2592000  

Oddly enough when I convert everything to Fixnum it's back to working as expected.

0> Time.utc(1999, 12, 29).to_i + 1.month.to_i - Time.utc(1999, 12, 29).to_i  => 2592000  

What is going on?

Rails 5 has many through association with fields_for - How write the form and controller?

Posted: 22 Oct 2016 11:42 PM PDT

I have model User

user.rb

class User < ApplicationRecord    has_many :team_user    has_many :teams, through: :team_user    accepts_nested_attributes_for :teams  end  

team.rb

class Team < ApplicationRecord    has_ancestry    has_many :team_user    has_many :users, through: :team_user    accepts_nested_attributes_for :users, allow_destroy: true  end  

team_user.rb

class TeamUser < ApplicationRecord    belongs_to :team    belongs_to :user  end  

I want to save the team members on the team page in a nested form. Should look like my html.erb and what should be in the controller?

No comments:

Post a Comment