Monday, November 28, 2016

Rails Devise Omniauth Facebook Login Not Redirecting to my website If user not previously Login | Fixed issues

Rails Devise Omniauth Facebook Login Not Redirecting to my website If user not previously Login | Fixed issues


Rails Devise Omniauth Facebook Login Not Redirecting to my website If user not previously Login

Posted: 28 Nov 2016 08:17 AM PST

I am using Omniauth To login users to my rails site with facebook. Following the tutorial i ve succesfuly login users, and following this i can do it in a popup (Turn omniauth facebook login into a popup) But i have problem with one specific case.

If the user is not previously login to facebook, then facebook ask for credentials. But after the signing in, the page stays in facebook and dont get back to my web page. But, i ve seen that my callback is being called, because if i do the login in a popup or new tab, and then refresh my original webpage, then the callback login has been called. So the Problem is only turning back the control to my web page if the user has to login to his facebook session. Any ideas?

This is my devise configuration config.omniauth :facebook, APP_ID, APP_SECRET, callback_url: "http://www..com/users/auth/facebook/callback", scope: 'email, public_profile', info_fields: 'email,name', :display => 'popup'

includes method in Ruby on Rails 3

Posted: 28 Nov 2016 08:16 AM PST

Why does includes method behaves like select distinct

One blog has many 10 comments.
includes output remove same record. But find_by_sql doesn't remove same record. why??

# includes  1.9.3-p551 :023 > Blog.includes(:comments).where(comments: {id: [1..40]})    SQL (0.6ms)  SELECT "blogs"."id" AS t0_r0, "blogs"."name" AS t0_r1, "blogs"."created_at" AS t0_r2, "blogs"."updated_at" AS t0_r3, "comments"."id" AS t1_r0, "comments"."blog_id" AS t1_r1, "comments"."created_at" AS t1_r2, "comments"."updated_at" AS t1_r3 FROM "blogs" LEFT OUTER JOIN "comments" ON "comments"."blog_id" = "blogs"."id" WHERE (("comments"."id" BETWEEN 1 AND 40 OR 1=0))   => [#<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">]     # find_by_sql  1.9.3-p551 :024 > Blog.find_by_sql("select blogs.* from blogs left outer join comments on comments.blog_id = blogs.id where (comments.id between 1 and 40)")    Blog Load (0.3ms)  select blogs.* from blogs left outer join comments on comments.blog_id = blogs.id where (comments.id between 1 and 40)   => [#<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">, #<Blog id: 1, name: nil, created_at: "2016-11-28 15:47:38", updated_at: "2016-11-28 15:47:38">]   

Using execute_script with a DateRangePicker

Posted: 28 Nov 2016 08:11 AM PST

I'm trying to do something like this: How to fill_in datepicker using Capybara, Rails, MiniTest spec, only for a DateRangePicker (http://www.daterangepicker.com/), and using separate statements to click the various parts of the daterangepicker.

This is my attempt:

page.execute_script %Q{ $('#push_notification_timespan2').trigger('click') }  page.execute_script %Q{ $('.next').trigger('click') }  page.execute_script %Q{ $('.table-condensed:contains("15")').trigger('click') }  page.execute_script %Q{ $('.applyBtn').trigger('click') }  

The classes listed in the last 3 statements are what I see when I inspect the various components of the daterangepicker.

My test fails with this message:

) Push Notification Campaign wizard create a one-time push notification   Failure/Error: page.evaluate_script("$('#push_notification_timespan2').daterangepicker('value','startDate'").should eq("Thu, Dec 15, 2016")       expected: "Thu, Dec 15, 2016"          got: nil       (compared using ==)  

Is there any way to tell if the individual page.execute_script lines have succeeded or failed? Any suggestions on how to make this work?

searchkick rails default_index analyzer not working

Posted: 28 Nov 2016 08:09 AM PST

I have the searchkick configured to Brazilian portuguese and the analyzers are not working properly.

  searchkick language: 'brazilian', merge_mappings: true, settings: {      number_of_shards: 2,      number_of_replicas: 0,      analysis: {        filter: {          brazilian_stop: {            type:       'stop',            stopwords:  '_brazilian_'          },          custom_stop: {            type: 'stop',            stopwords: %w(eu)          },          brazilian_stemmer: {            type:       'stemmer',            language:   'brazilian'          }        },        analyzer: {          default_index: {            tokenizer:  'standard',            filter: %w(              lowercase              brazilian_stop              brazilian_stemmer              custom_stop            )          }        }      }    }  

My search method is:

  def self.search_by(text, user_id)      search(        text,        where: { user_id: user_id },        fields: ['text'],        operator: 'or'      )    end  

For example: for the string: "Quais as vantagens?" and "Vantagens" the method call Model.searchkick_index.tokens(string) returns:

Model.searchkick_index.tokens('Quais as vantagens ? ') #=> ["vantagens"]    Model.searchkick_index.tokens('Vantagens') #=> ["vantagens"]  

But the elasticsearch score for each search is very different:

Model.search_by('vantagens', 1).response['hits']['hits'][0]['_score'] #=> 3.224    Model.search_by('Quais as vantagens ?', 1).response['hits']['hits'][0]['_score'] #=> 0.047  

Does anyone know how I use my analyzer with searchkick to searchkick_search.tokens represents the real search in elasticsearch?

AJAX call to rails controller for image not finding correct file path

Posted: 28 Nov 2016 08:08 AM PST

I have an image that is reachable in ruby by

<%= image_tag(@user.avatar.url(:thumb)) %>  

Images are stored using paperclip, and there is a default missing url set in the users model:

has_attached_file :avatar, :styles => { :medium => "200x200#", :thumb => "100x100#" }, :default_url => ":style/missing.png"

There is a handlebars template that needs to render this same image. So, I created a get_image method in the users_controller, but it does not return the correct url for the missing image (it does for users with images), and just shows a broken image picture.

def get_image      user_id = params[:userId]      user = User.find(user_id)      @user_image = user.avatar        render json: @user_image, :status => 200   end  

and calling it in application.js:

function getUserImage(userId)   {          return $.ajax({               type: "GET",              url: '/get_image',              data: {                  userId: userId              },              success: function(result)   {                     console.log(result)                  userImage = result;                  return userImage;              },              error: function(err)    {                  console.log(err);              }            });      };  

The result is http://localhost:3000/profile/original/missing.png

The ruby image_tag returns: http://localhost:3000/assets/medium/missing-e38aa1831b278c511eff9812efc6fda028d46b3b94f71cc88c3e0ba0e99ff19e.png

The ruby one works, the other does not. How to do I get it to call the correct image path? Thanks!

Excon::Error::Forbidden (Expected(200) <=> Actual(403 Forbidden) Uploading from Heroku to Amazon s3

Posted: 28 Nov 2016 08:04 AM PST

I am trying to use AWS S3 for uploading images with Carrierwave but i am getting this error in the Heroku logs:

Completed 500 Internal Server Error in 183ms (ActiveRecord: 3.0ms)  2016-11-28T15:50:11.497129+00:00 app[web.1]:   Excon::Error::Forbidden (Expected(200) <=> Actual(403 Forbidden)  

I have tried everything, from creating new users in my AWS account and giving them AdminAccess then changing the access Keys in the heroku console but doesn´t to work.

I leave here some of my app files in case sombody knows what could be the problem..

initializers/carrierwave.rb

CarrierWave.configure do |config|    config.root = Rails.root.join('tmp') # adding these...    config.cache_dir = 'carrierwave'    config.fog_provider = 'fog/aws'                        # required    config.fog_credentials = {      provider:              'AWS',                        # required      aws_access_key_id:     ENV["AWS_ACCESS_KEY_ID"],                            # required      aws_secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"],                        # required      region:                'us-east-1',        host:                  's3-us-east-1.amazonaws.com',             # optional, defaults to nil                # optional, defaults to 'us-east-1'      endpoint:              'https://s3.amazonaws.com' # optional,   defaults to nil    }    config.fog_directory  = ENV["AWS_BUCKET_NAME"]                          # required    config.fog_public     = false                                        # optional, defaults to true    config.fog_attributes = { 'Cache-Control' => "max-age=#{365.day.to_i}" } # optional, defaults to {}  end  

image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base     storage :fog  end  

Gemfile

source 'https://rubygems.org'  ruby "2.2.2"    gem 'rails', '4.2.6'  gem 'sass-rails', '~> 5.0'  gem 'uglifier', '>= 1.3.0'  gem 'coffee-rails', '~> 4.1.0'  gem 'jquery-rails'  gem 'turbolinks'  gem 'jbuilder', '~> 2.0'  gem 'sdoc', '~> 0.4.0', group: :doc  gem 'bourbon'  gem 'neat'  gem 'devise'  gem 'carrierwave', '>= 1.0.0.rc', '< 2.0'  gem 'will_paginate', '~> 3.1.0'  gem "fog-aws"        group :development, :test do    gem 'byebug'  end    group :development do    gem 'web-console', '~> 2.0'    gem 'spring'    gem 'sqlite3'  end    group :production do      gem 'pg'      gem 'rails_12factor'  end  

Thanks a lot!

Postgresql, "Gem::LoadError: pg is not part of the bundle. Add it to Gemfile."

Posted: 28 Nov 2016 08:01 AM PST

I am running on a Windows.

On my Project, I did a Bundle Install with no errors. Then I try to do rake db:create, it says enter image description here

enter image description here

I did a gem install pg, which worked but I still get this error. Judging by the error, I think it is saying that it doesn't recognize PostgreSQL installed on my computer but I do have it installed. I have 9.6 installed: enter image description here

I also created an Environment Path but to no result. What am I missing here?

Unable to associate User and Profile Model

Posted: 28 Nov 2016 08:24 AM PST

I'm still relatively new to Ruby on Rails so I'm trying to figure this one out. I've done a lot of research so far but can't figure out how to tie it altogethe so that both my User & Profiles model associate with each other AND allow my Profile to save. - I'm using the Devise gem, which registers a new user through the Registrations Controller. - I have created a Profiles Controller. - When a User registers, they are automatically brought to the Profile new.html.erb page to setup their profile. However, when I try to save it, nothing happens. However, if I remove the 'belongs_to :users' line of code under the ProfilesController, then I can save it without issue but it obviously doesn't associate it with the user.

  • I have created the relationship between the 2 models where a User should have only 1 profile. I've also created a user_id in the Profiles table to act as a foreign key to link the 2 tables.

My User model:

class User < ApplicationRecord    # Include default devise modules.    devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable      has_one :profile, dependent: :destroy    accepts_nested_attributes_for :profile  end  

My Profile model:

class Profile < ApplicationRecord    belongs_to :user    #after_create :create_profile  end  

My Schema.

ActiveRecord::Schema.define(version: 20161126221219) do      create_table "profiles", force: :cascade do |t|      t.string   "full_name"      t.string   "contact_number"      t.string   "location"      t.string   "makeup_type"      t.string   "bio"      t.datetime "created_at",     null: false      t.datetime "updated_at",     null: false      t.integer  "user_id"      t.string   "image"    end      create_table "users", force: :cascade do |t|      t.string   "name",                   default: "", null: false      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.index ["email"], name: "index_users_on_email", unique: true      t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true    end  end  

My Profiles Controller:

class ProfilesController < ApplicationController   before_action :set_profile, only: [:show, :edit, :update, :destroy]      def index      @search = Profile.search(params[:q])      @profiles = @search.result(distinct: true)    end      def show      @profile = Profile.find(params[:id])    end      def new      @profile = Profile.new      end      def create      @profile = Profile.new(profile_params)        respond_to do |format|      if @profile.save        format.html { redirect_to @profile, notice: 'Your Profile was successfully created' }        format.json { render :show, status: :created, location: @profile }      else        format.html { render :new }        format.json { render json: @profile.errors, status: :unprocessable_entry }      end    end     end      def edit      @profile = Profile.find(params[:id])    end      def update      respond_to do |format|        if @profile.update(profile_params)        format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }        format.json { render :show, status: :ok, location: @profile }      else        format.html { render :edit }        format.json { render json: @profile.errors, status: :unprocessable_entity }      end    end  end      def destroy      @profile.destroy        respond_to do |format|        format.html { redirect_to profile_url, notice: 'Profile was successfully destroyed.' }        format.json { head :no_content }      end    end      def set_profile      @profile = Profile.find(params[:id])    end      private      def profile_params        params.require(:profile).permit(:full_name, :contact_number, :location, :makeup_type, :bio, :user_id, :image)      end      end  

I created a Users controller, which isn't created when setting up Devise but I wanted to override some of the actions. However, this is where I get stuck as I'm not sure what methods I'm supposed to override and how to do it as Devise is creating the user profile. Anyway, my User controller is below:

class UsersController < ApplicationController      def show      @user = User.find(params[:id])    end  end  

Lastly, I created a RegistrationsController to override the Devise Registrations controller so I could route the registration page to the Profiles new.html.erb page below.

class RegistrationsController < Devise::RegistrationsController   # before_action :configure_sign_up_params, only: [:create]   # before_action :configure_account_update_params, only: [:update]     protected  # This allows a newly registered user to be directed to the Profile Creation page  def after_sign_up_path_for(resource)    new_profile_path(resource)  end      def after_sign_in_path_for(resource)      profile_path(resource)    end  end  

How do I install libxml-ruby gem 2.3.2 on OSX El Capitan?

Posted: 28 Nov 2016 07:53 AM PST

I am trying to install an old project that runs on Ruby 1.8.7-p370 and has a dependency on an old version of the libxml-ruby 2.3.2 gem on a Mac running OS X El Capitan.

The problem is upon trying to install the gem it won't build the native extension. Here is the complete error upon running gem install libxml-ruby -v '2.3.2':

Building native extensions.  This could take a while...  ERROR:  Error installing libxml-ruby:      ERROR: Failed to build gem native extension.            /Users/myusername/.rbenv/versions/1.8.7-p370/bin/ruby extconf.rb  checking for socket() in -lsocket... no  checking for gethostbyname() in -lnsl... no  checking for atan() in -lm... no  checking for atan() in -lm... yes  checking for inflate() in -lz... yes  checking for iconv_open() in -liconv... yes  checking for xmlParseDoc() in -lxml2... yes  checking for libxml/xmlversion.h... yes  creating extconf.h  creating Makefile    make  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c libxml.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_attr.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_attr_decl.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_attributes.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_cbg.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_document.c  couldn't understand kern.osversion `15.6.0'  ruby_xml_document.c: In function 'rxml_document_canonicalize':  ruby_xml_document.c:334: warning: passing argument 4 of 'xmlC14NDocDumpMemory' from incompatible pointer type  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_dtd.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_encoding.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_error.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_html_parser.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_html_parser_context.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_html_parser_options.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_input_cbg.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_io.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_namespace.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_namespaces.c  couldn't understand kern.osversion `15.6.0'  /usr/local/bin/gcc-4.2 -I. -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include -DRUBY_EXTCONF_H=\"extconf.h\" -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE  -I/Users/myusername/.rbenv/versions/1.8.7-p370/include  -fno-common  -O3 -Wno-error=shorten-64-to-32  -pipe -fno-common  -I/usr/include/libxml2 -I. -I/Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/1.8/i686-darwin15.6.0 -I. -I/usr/local/include  -c ruby_xml_node.c  couldn't understand kern.osversion `15.6.0'  ruby_xml_node.c: In function 'rxml_node_to_s':  ruby_xml_node.c:622: error: dereferencing pointer to incomplete type  ruby_xml_node.c:624: error: dereferencing pointer to incomplete type  make: *** [ruby_xml_node.o] Error 1      Gem files will remain installed in /Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/gems/1.8/gems/libxml-ruby-2.3.2 for inspection.  Results logged to /Users/myusername/.rbenv/versions/1.8.7-p370/lib/ruby/gems/1.8/gems/libxml-ruby-2.3.2/ext/libxml/gem_make.out  

I have done some Googling but so far have not found a solution to the problem that works. Here are some of the things I have tried.

One suggestion was that uninstalling apple-gcc might work, but that leaves me without a compiler to build the native extension.

Another post suggested that this has to do with an incompatibility between libxml-ruby 2.3.2 and the more recent version of libxml that ships with OS X. However the following does not work since the MacOSX10.8 SDK does not seem to ship with Xcode anymore. Or am I missing something there?

export SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk  

What steps can I take to remedy this problem? Thanks for your help!

Callback run at a datatime specified in the rails database

Posted: 28 Nov 2016 07:57 AM PST

I have a rails API that has a Transaction ActiveRecord model. When a transaction object is created, it withdraws the money from your account if there is enough. Transaction has a field called fulfilled of type boolean, and one called expires_at which is of type datetime. What I want to do is run a cleanup-routine at exactly the expires_at time that will destroy the record if fulfilled is true, therefore calling the before_destroy callback in the model.

How can I run code at the datetime specified in a database field? I want to either destroy the object at that time or simply reverse the transaction.

What is the standard way to access a controller action that modifies server data but isn't a CRUD operation?

Posted: 28 Nov 2016 07:59 AM PST

I have a Ruby on Rails API. One of the ActionRecord models is a transaction. I want to be able to use a link such as http://localhost:3000/transactions/1/fulfill, where 1 is the id of the transaction in the database.

As I understand it, a GET request should be avoided since data on the server is modified through the action. Would I then use a POST request or a PUT request? Is it okay if the request body is empty in the call?

ActiveRecord::AssociationTypeMismatch Device(#xxxx) expected, got String(#xxxx)

Posted: 28 Nov 2016 07:59 AM PST

I'm getting the following error... ActiveRecord::AssociationTypeMismatch Device(#xxxx) expected, got String(#xxxx)

I cant see to work out where this error is coming from or how to solve it. Can anyone explain where my code is going wrong?

Models =

class Device < ActiveRecord::Base      has_many :from_links, class_name: "Link", foreign_key: "from_device"    has_many :to_links, class_name: "Link", foreign_key: "to_device"      def connected_devices      from_links.map(&:to_device) + to_links.map(&:from_device)    end  end    class Link < ActiveRecord::Base      belongs_to :from_device, class_name: "Device"    belongs_to :to_device, class_name: "Device"  end  

LinksController =

class LinksController < ApplicationController    def create      @link = Link.new(link_params)      @device = Device.find_by(en: params[:link][:from_device])      if @link.save        flash[:success] = "Link created."        redirect_to device_path(@device)      else        render 'new'      end    end     private       def link_params       params.require(:link).permit(:from_device, :to_device, device_attributes: [:en])     end  end  

DevicesController =

class DevicesController < ApplicationController      def show      @device = Device.find(params[:id])      @linked_devices = @device.connected_devices    end    private      def device_params      params.require(:device).permit(:name, :en, :system_ip, :router_ip, :pop, :chassis_mode, :code_version)    end  

CreateLinks Database =

class CreateLinks < ActiveRecord::Migration[5.0]    def change      create_table :links do |t|        t.references :from_device        t.references :to_device      end    end  

Create New Link Form =

<% provide(:title, 'New Link') %>  <h1> Create New Link </h1>    <div class="row">  <div class="col-md-6 col-md-offset-3">    <%= form_for(@link, url: links_path(params[:id])) do |f| %>      <%= render 'shared/error_messages', object: @link %>        <%= f.label :from %>      <%= f.select :from_device, options_for_select(@devices), :include_blank => true, class: 'form-control' %>        <%= f.label :to %>      <%= f.select :to_device, options_for_select(@devices), :include_blank => true, class: 'form-control' %>        <%= f.submit "Submit", class: "btn btn-primary" %>    <% end %>  </div>  

How does Rails keep the form data when validations fail?

Posted: 28 Nov 2016 07:47 AM PST

I have an 'create' action method in Rails and do:

def create    @movie = Movie.new(movie_params)    if @movie.save      redirect_to @movie, notice: "Movie successfully created"    else      render :new    end  end  

Now, I have a few validations in place for the Movie model. In case those validations fail, and @movie.save returns false, I simply invoke the new template (without touching the new action, since render :new is the same as render template: 'new'.

I don't understand how Rails can keep the form data I already entered when it again renders that new view. What's going on behind the hood that allows it to do this?

Postgres Order different between Development and Production

Posted: 28 Nov 2016 07:04 AM PST

In the Rails controller:

Item.all.order(:reading)  

Order output in Development: け, けけ, けけけ, す, すす, すすす

Order output in Production (Heroku): け, す, けけ, すす, けけけ, すすす

It appears first sorted by length, then properly 'alphabetically'. Repo: https://github.com/BuSensei/busensei

Mocks: RSpec and Rails

Posted: 28 Nov 2016 06:53 AM PST

Writing an rspec test that, in addition to other things, checks for the existence of a table given a query string.

Currently, the test for finding a model given a query string returns uninitialized constant QueryStringName. I know this means that the system under test cannot find a model class named QueryStringName.

I would like to implement a fake model object because I don't want to think about its implementation details (associations, attributes etc) right now. And I think I can handle this by creating some sort of fake model, which I believe is called a double. Am I right?

Another problem is that I am not exactly sure how to go about this. I tried this:

        context 'when table exists' do             it 'finds correct database table' do               expect(subject.find_model).to be_a(Class)            end          end    

It should be noted that subject.find_model implements the following:

   def find_model       # get_class_name = self.query_string.classify       get_class_name.constantize     end   

I thought to do something like this: QueryStringName = double("QueryStringName")

    context 'when table exists' do         it 'finds correct database table' do           QueryStringName = double("QueryStringName")          expect(QueryStringName).to be_a(Class)        end      end  

but that doesn't work.

I would appreciate it if someone could explain how to implement fake objects in test.

Thank you.

PS: using rspec-rails, '~> 3.5

javascript not working when added via asset pipeline

Posted: 28 Nov 2016 06:46 AM PST

I want to implement bootstrap themes to my rails application

http://startbootstrap.com/template-overviews/creative/

in that theme there is a file named creative.js

I have add it to my application via asset pipeline

and when I load the page and use inspect element I can see it under sources tab and I can open it

But the script not worked

but If I copy paste the code and put it in my html It worked properly

my application.js

//= require jquery  //= require jquery_ujs  //= require turbolinks  //= require bootstrap-sprockets  //= require creative  //= require_tree .  

creative.js

(function($) {        "use strict"; // Start of use strict          // jQuery for page scrolling feature - requires jQuery Easing plugin        $('a.page-scroll').bind('click', function(event) {            var $anchor = $(this);            $('html, body').stop().animate({                scrollTop: ($($anchor.attr('href')).offset().top - 50)            }, 1250, 'easeInOutExpo');            event.preventDefault();        });          // Highlight the top nav as scrolling occurs        $('body').scrollspy({            target: '.navbar-fixed-top',            offset: 51        });          // Closes the Responsive Menu on Menu Item Click        $('.navbar-collapse ul li a').click(function() {            $('.navbar-toggle:visible').click();        });          // Offset for Main Navigation        $('#mainNav').affix({            offset: {                top: 100            }        })          // Initialize and Configure Scroll Reveal Animation        window.sr = ScrollReveal();        sr.reveal('.sr-icons', {            duration: 600,            scale: 0.3,            distance: '0px'        }, 200);        sr.reveal('.sr-button', {            duration: 1000,            delay: 200        });        sr.reveal('.sr-contact', {            duration: 600,            scale: 0.3,            distance: '0px'        }, 300);          // Initialize and Configure Magnific Popup Lightbox Plugin        $('.popup-gallery').magnificPopup({            delegate: 'a',            type: 'image',            tLoading: 'Loading image #%curr%...',            mainClass: 'mfp-img-mobile',            gallery: {                enabled: true,                navigateByImgClick: true,                preload: [0, 1] // Will preload 0 - before current, and 1 after the current image            },            image: {                tError: '<a href="%url%">The image #%curr%</a> could not be loaded.'            }        });      })(jQuery); // End of use strict  

my application.html.erb

<!DOCTYPE html>  <html lang="en">    <head>        <meta charset="utf-8">      <meta http-equiv="X-UA-Compatible" content="IE=edge">      <meta name="viewport" content="width=device-width, initial-scale=1">      <meta name="description" content="">      <meta name="author" content="">        <title>Creative - Start Bootstrap Theme</title>      <%= csrf_meta_tags %>        <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>        <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>      <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>        <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->      <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->      <!--[if lt IE 9]>          <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>          <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>      <![endif]-->    </head>      <body id="page-top">      <%= yield %>      <script>        creative.js code here      </script>    </body>  </html>  

Destroying object without its ID

Posted: 28 Nov 2016 07:37 AM PST

I'm creating LIKE model to my rails application. Routing is:

resources :bonuses, only: %i(index create) do    resources :likes, only: %i(create destroy)  end  

I did a create of like and now trying to make a dislike button. I want to delete like with this button:

= link_to "Dislike", bonus_like_path, method: :delete  

But i get error here: missing required keys: [:bonus_id, :id] If I pass the bonus_like_path(bonus) I will miss the ID parameter of like(but I dont need him, I know user.id)

To delete like everything that I need to know is bonus_id and current_user.id

schema.rb (likes)

create_table "likes", force: :cascade do |t|    t.integer "user_id",  null: false    t.integer "bonus_id", null: false    t.index ["user_id", "bonus_id"], name: "index_likes_on_user_id_and_bonus_id", unique: true, using: :btree  end  

The associations are simple:

Bonus:

has_many :likes, dependent: :destroy  has_many :liked_users, through: :likes, source: :user  

User:

has_many :likes, dependent: :destroy  has_many :liked_bonus, through: :likes, source: :bonus  

Like:

belongs_to :bonus, counter_cache: true, touch: true  belongs_to :user  

So I understand that I can make DELETE bonus_like_path(bonus) request because user already defined in current_user. But don't know how to write it correctly.

ActiveRecord::Fixture::FixtureError: table "books" has no column named "loves"

Posted: 28 Nov 2016 06:52 AM PST

Bizarre Rails problem.

I have a Book entity and users can Love a book.

All my other models are fine and passing all the tests but after generating the new Love model and setting the fixtures, I am getting a ton of these errors out of the blue:

ActiveRecord::Fixture::FixtureError: table "books" has no column named "loves".  

I somehow think it's to do with reserved keywords in Rails perhaps?

Is Love a reserved keyword by any chance?

I did a search on this page:

https://reservedwords.herokuapp.com/

And the word love yields no results.

Love Migration File

class CreateLoves < ActiveRecord::Migration[5.0]    def change      create_table :loves do |t|        t.references :book, foreign_key: true        t.references :sender, foreign_key: true        t.references :receiver, foreign_key: true          t.timestamps      end    end  end  

Love Model

class Love < ApplicationRecord    belongs_to :book    belongs_to :sender, class_name: "User"    belongs_to :receiver, class_name: "User"  end  

Love Fixtures

one:    book: one    sender: jim    receiver: sarah    two:    book: two    sender: sarah    receiver: jim    three:    book: three    sender: jim    receiver: tycus  

Book Model

class Book < ApplicationRecord    belongs_to :author, class_name: "User"    has_and_belongs_to_many :genres    has_many :loves  end  

Book Fixtures

one:    title: Back To The Future    adult_content: true    author: jim    published: false    genres: action, comedy, science_fiction    two:    title: Harry Potter and The Philosopher's Stone    adult_content: false    author: sarah    published: false    genres: action, fantasy    three:    title: Back To The Future 2    adult_content: true    author: jim    published: false    genres: action, comedy, science_fiction    four:    title: Back To The Future 3    adult_content: true    author: jim    published: false    genres: action, comedy, science_fiction    five:    title: Royal Guard    adult_content: true    author: chewedon    published: false    genres: action, romance, fantasy  

Books Controller

class BooksController < ApplicationController    before_action :authenticate_user    after_action :verify_authorized, except: [:index, :create]    after_action :verify_policy_scoped, only: :index      def index      books = policy_scope(Book.all)      render json: books    end      def create      book = Book.new(book_params)        if book.save        render json: book, status: :created      else        render status: :unprocessable_entity      end    end      def show      book = Book.find_by(id: params[:id])        if book.present?        authorize book        render json: book      else        skip_authorization        render status: :not_found      end    end      def update      book = Book.find_by(id: params[:id])        skip_authorization and render status: :not_found and return unless book        authorize book        if book.update!(book_params)        render json: book      else        render status: :unprocessable_entity      end    end      def destroy      book = Book.find_by(id: params[:id])        skip_authorization and render status: :not_found and return unless book        authorize book        if book.destroy!        render status: :ok      end    end        private      def book_params      params.permit(:title, :adult_content, :published, :author_id, genre_ids: [])    end  end  

Here are some of my other model and their test fixtures, they all pass the tests:

Chapter Fixtures

one:    title: Straw House    order: 1    content: First pig built a house out of straw    published: true    book: one    two:    title: Wooden House    order: 2    content: Second pig built a house out of wood    published: true    book: one    three:    title: Brick House    order: 3    content: Third pig built a house out of brick    published: false    book: one    four:    title: Hogwarts School of Wizardry    order: 1    content: They pushed their troller into nine and three quarters    published: false    book: two  

Comment Fixtures

one:    content: Love this chapter    author: jim    book: one    chapter: one    two:    content: Hate this chapter    author: sarah    book: two    chapter: two    three:    content: Interesting chapter    author: tycus    book: one    chapter: one  

Message Fixtures

one:    subject: Next Chapter    body: When will the next chapter be published?    sender_read: false    receiver_read: false    sender: jim    receiver: sarah    two:    subject: Film Adaptation    body: I would like to turn your story into a film    sender_read: false    receiver_read: false    sender: sarah    receiver: jim    three:    subject: Mind Blown    body: Where do you get all these ideas? I'll stalk you now!    sender_read: false    receiver_read: false    sender: tycus    receiver: jim  

What could be the problem?

Update

If I comment out my Love Fixtures:

# one:  #   book: one  #   sender: jim  #   receiver: sarah  #  # two:  #   book: two  #   sender: sarah  #   receiver: jim  #  # three:  #   book: three  #   sender: jim  #   receiver: tycus  

I get new test errors:

Error:  BooksControllerTest#test_book_show_-_should_show_book_info:  NameError: uninitialized constant Book::Lofe      app/controllers/books_controller.rb:26:in `show'      test/controllers/books_controller_test.rb:63:in `block in <class:BooksControllerTest>'  

Where the heck did "Lofe" come from?

I quadruple checked my spelling of Love. I even did an entire project search for word "Lofe" and it doesn't show any search results matching.

rails + print page from printer without any human intraction

Posted: 28 Nov 2016 06:11 AM PST

I want to print a pdf from any printer directly, there should be no human interaction, Example after create a invoice , it can be printable through printer.

Rails passing params with link_to using ajax

Posted: 28 Nov 2016 06:20 AM PST

I'm creating a online order system for a restaurant using rails and i want to be able to attach modifiers to items using ajax i have

<%= link_to(mod.name , add_modifier_url , method: :put, remote: true, mod_id: mod.id, item_id: item.id) %>  

the call is making it to my controller but i cant access any of the params I'm sending how do you pass params with link_to and ajax in rails

thanks

EDIT

I think I answered my own question, I just had to put the params i wanted to send as params for the url

<%= link_to(mod.name , add_modifier_url( mod_id: mod.id, item_id: item.id) , method: :put, remote: true) %>  

Rails direct method to update join table association?

Posted: 28 Nov 2016 06:47 AM PST

I am looking for a direct method to update a jointable asociation

An example is: I have Project (id: 45) and some people are working on it (Person id 10 and Person id 12)

The jointable is persons_projects whith

...  person_id: 10 project_id: 45  person_id: 12 project_id: 45  ...  

And in some point the people leave, arrive and or not. Example Person id 12 leave, Person id 10 stay and Person id 33 arrive.

The "long" way was to insert to persons_projects check actual people [10 , 33] and check on old people [10,12] if not exist create and to delete in persons_projects check the old people in new people, if not exist delete them.

This take 2 loop, but I think there are a ruby short method like

Project.persons.delete_or_create_bla([10 , 33])  

Ruby, ActiveRecord: Local rails server updates record attributes whereas the remote server does not

Posted: 28 Nov 2016 06:18 AM PST

I have a script which sends data from a Windows back end to Heroku. Recently I added four new columns to the object model. For testing each of the properties is updated individually through a cURL request.

On the local rails server (which is identical to the Heroku hosted server) all four new attributes are populated correctly and there are no errors in the logs.

On the Heroku based server when I run the back end script it updates two of the columns but not the other two. In spite of these values not being populated the logs indicate that the process ran successfully with status of 200.

Has anyone experienced something similar to this?

How to test for the root in rails

Posted: 28 Nov 2016 05:47 AM PST

How do I correctly test for the route in rails? I have changed my posts#index to be my root in the routing file:

Rails.application.routes.draw do    get 'static_pages/home'    resources :posts    root 'posts#index'   end  

I have:

require 'test_helper'    class PostsControllerTest < ActionDispatch::IntegrationTest        test "should get root" do          get /          assert_response :success        end    # test "the truth" do    #   assert true    # end  end  

But the error comes up as:

syntax error, unexpected tSYMBEG, expecting keyword_do or '{' or '(' (SyntaxError) assert_response :success  

However my static_pages controller test works:

require 'test_helper'    class StaticPagesControllerTest < ActionDispatch::IntegrationTest      test "should get home" do      get static_pages_home_url      assert_response :success    end    end  

Rails - Strong Params on a Module?

Posted: 28 Nov 2016 05:30 AM PST

My controllers need to create more than one model. I could use nested attributes to whitelist the params. However I would have strong params for the same models all over the place and whenever I changed one of the models I would have to change all the strong params.

To solve this, I found this idea of creating a module with the strong params and call them in the controllers. I am new to rails, so I would like to know if this is a good or bad pattern/idea??

Forced validations for associated fields

Posted: 28 Nov 2016 06:22 AM PST

I am using rails 5.0.0.1

When I submit a form, validations for associated fields are coming into action.

I have Gig, User, Category and other models

I am using devise for user authentication

Gig model

class Gig < ActiveRecord::Base    has_many :proposals    belongs_to :category    has_many :abilities    has_many :skills, through: :abilities    belongs_to :user  end  

User model

class User < ApplicationRecord    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable      has_many :gigs    has_many :proposals  end  

Category model

class Category < ActiveRecord::Base    has_many :gigs  end  

When I try to create the gig in console, the transaction rolls back.

the error messages are

["Category must exist", "User must exist"]

I appreciate your help. Thanks in advance.

How to filter out all params of a POST request?

Posted: 28 Nov 2016 05:36 AM PST

I am making the following POST request to some_action in the ApiController:

HTTParty.post( 'https://example.com/api/some_action.json?token=foo',                 headers: {'Content-Type' => 'application/json'},                 body: {some_key: 'some_value'}.to_json               )  

I am trying to filter out the content of the submitted body, because it contains sensitive information. However, my log writes:

Started POST "/api/some_action.json?token=[FILTERED]" for 127.0.0.1 at 2016-11-28 12:30:32 +0100  Processing by ApiController#some_action as JSON    Parameters: {"some_key"=>"[FILTERED]", "token"=>"[FILTERED]", "api"=>{"some_key"=>"[FILTERED]"}}  

When I expect the params I get the params I get:

def some_action    Rails.logger.error params    # => {"some_key"=>"some_value", "token"=>"foo", "controller"=>"api", "action"=>"some_action", "format"=>"json", "api"=>{"some_key"=>"some_value"}}  end  

It seems that there is an extra param called api, which I suppose refers to the controller name. But I can't filter it. I can filter some_key param, but not the entire api param. Any idea how I can filter the api and how I can avoid to have the params written twice in the log? I have tried the following without success:

config.filter_parameters += [:api, :some_key]  

Ruby on rails - reading values from a text field

Posted: 28 Nov 2016 05:44 AM PST

So let's say I have the following text fields in my html.erb code:

<p> Field 1:    <%= text_field_tag 'field1' %>  <p> Field 2:    <%= text_field_tag 'field 2' %>  

And I would like to do the following:

<%= link_to "NextPage",              :controller => "MyController",              :action => "my_method",              :textfield1 => <%-# Read what has been entered in field1 -%>,              :textfield2 => <%-# Read what has been entered in field2 -%> %>  

How would I do that? I haven't found a way to read what the user enters in filed 1 (or field 2) in order to add it as a parameter for textfield1 and textfield2 in the link.

how to drag and drop an from many items in token field and drop same ro another place

Posted: 28 Nov 2016 04:19 AM PST

Iam implanting mail client . I want to add drag and drop field. Now can't drag any element which are render token field. like.. enter image description here

i am already tranfer normal text..when add token field that text box is no working. the code are... inbox.html.erb

cc Bcc
   <br>         <div class="form-group" id="cc_div_id" style="display: none">       <div class="col-xs-1"> <%= label_tag :"CC:" %> </div>       <div class="col-sm-8" id="droppable">  <%= text_field_tag :cc,"",    class:'form-control', placeholder: "Recipients" %></div>     </div>  

javascript.js

$(function() {  $("#to-tokenfield").draggable({      revert: true,      helper: 'clone',      start: function(event, ui) {          $(this).fadeTo('fast', 0.5);      },      stop: function(event, ui) {          $(this).fadeTo(0, 1);      }  });    $("#droppable").droppable({      hoverClass: 'active',      drop: function(event, ui) {          this.value = $(ui.draggable).text();      }  });  });  

search association having class_name

Posted: 28 Nov 2016 04:24 AM PST

i have a Book model looking like this:

class Book < ActiveRecord::Base    belongs_to :author, class_name: 'User', touch: true    belongs_to :translator, class_name: 'User'  end  

How can i search for books with specific author name? i join the tables first:

Book.joins(:author).joins(:translator)  

But i cant chain

.where('authors.name = "Tolkien"')  

because there is no "authors" table in the database. is

.where('users.name = "Tolkien"')  

a safe approach here? is there no risk concerning both translators and authors being users in fact? (select() method is not an option, i need activerecord::relation here)

Is ot possible to update list feed page using actioncable?

Posted: 28 Nov 2016 05:46 AM PST

My app contains a feed page where multiple posts are posted. I want to that feed page is updated automatically using action cable. I want to know is it possible and how?

If you only help by saying yes or no that also helpful for me :)

No comments:

Post a Comment