Saturday, September 17, 2016

Rails: Read image source/remote_url and show image as my own image on my website | Fixed issues

Rails: Read image source/remote_url and show image as my own image on my website | Fixed issues


Rails: Read image source/remote_url and show image as my own image on my website

Posted: 17 Sep 2016 07:45 AM PDT

I need to do something similar to following in my rails app. Suppose there is an image on flickr. I need to read that image and show at my own website url.

suppose image is at: http://www.flickr.com/some_image.jpg

I need to show that image at http://my-website.com/some-image.jpg

The user should not realize that it's coming from any other website. The output should be cached for future request.

How do I do that in rails.

thanks,

live search page with ReactJS, Rails and Elasticsearch searchkick

Posted: 17 Sep 2016 07:21 AM PDT

i am new to react and i am using this tutorial to do a live search in my rails app with react-rails https://blog.skcript.com/building-a-live-search-page-with-reactjs-rails-and-elasticsearch-197f2650438b#.wce536mw3

I am trying to do a search through profiles here is my profiles_controller.rb

class ProfilesController < ApplicationController      before_action :set_profile, only: [:show, :edit, :update, :destroy]        # GET /profiles      # GET /profiles.json      def index        @profiles = Profile.all        if params[:search]          @profiles = Profile.search(params[:search]).order("created_at DESC")        else          @profiles = Profile.all.order("created_at DESC")        end       end        def search        @profiles = Profile.search(params[:query])        if request.xhr?          render :json => @profiles.to_json        else          render :index        end        require 'pry'; binding.pry      end        def admin        @profile = Profile.new        @profiles = Profile.all      end          def table        @profiles = Profile.all      end          # GET /profiles/1      # GET /profiles/1.json      def show      end        # GET /profiles/new      def new        @profile = Profile.new      end        # GET /profiles/1/edit      def edit      end        # POST /profiles      # POST /profiles.json      def create        @profile = Profile.new(profile_params)          respond_to do |format|          if @profile.save            format.html { redirect_to admin_path, notice: 'Profile was successfully created.' }            format.json { render :show, status: :created, location: @profile }          else            format.html { redirect_to admin_path, notice: 'You didnt put in some important values pls ensure you fix in the important ones, The starred ones must be filled to save or profile is already available' }            format.json { render json: @profile.errors, status: :unprocessable_entity }          end        end      end        # PATCH/PUT /profiles/1      # PATCH/PUT /profiles/1.json      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        # DELETE /profiles/1      # DELETE /profiles/1.json      def destroy        @profile.destroy        respond_to do |format|          format.html { redirect_to profiles_url, notice: 'Profile was successfully destroyed.' }          format.json { head :no_content }        end      end        private        # Use callbacks to share common setup or constraints between actions.        def set_profile          @profile = Profile.find(params[:id])        end          # Never trust parameters from the scary internet, only allow the white list through.        def profile_params          params.require(:profile).permit(:first_name, :middle_name, :last_name, :myjob, :education, :age, :net_worth,                          :source1, :source2, :source3, :description, :avatar, :mycountry, :mystate)        end    end  

I keep getting this error in my log

Started GET "/search?query=o" for ::1 at 2016-09-17 15:10:50 +0100  Processing by ProfilesController#search as JSON    Parameters: {"query"=>"o"}  Completed 500 Internal Server Error in 9ms (ActiveRecord: 0.0ms)    Faraday::ConnectionFailed (Connection refused - connect(2) for "localhost" port 9200):    app/controllers/profiles_controller.rb:16:in `search'  

I have researched and found in this stackoverflow answer to add Searchkick.client = Elasticsearch::Client.new(hosts: ["localhost:9200"], retry_on_failure: true, transport_options: {request: {timeout: 250}}) to an initializer so I created a searchkick.rb file in initializers folder and added that line of code but still getting the same error please does anyone know why I am getting that error.

When I try to search it doesnt return anything like its not working at all

Ruby on Rails - Running rails server on a public IP

Posted: 17 Sep 2016 06:35 AM PDT

Is it possible to perform a

rails server -b my.public.ip.address -p 8000  

running this code obviously doesn't work. So I am wondering if there is a way to around this?

How do I use lookup_context to make this view as DRY as possible?

Posted: 17 Sep 2016 05:16 AM PDT

For starters, this is the view I am trying to replicate:

screenshot of grades layout

This is the HTML from that layout (from the SAT portion anyway, you can extrapolate the rest):

<table class="table table-hover table-bordered">                          <thead>                          <td colspan="2" class="text-center">                            <strong>SAT</strong>                          </td>                          <tr>                              <th>Subject</th>                              <th>Grade</th>                          </tr>                          </thead>                          <tbody>                          <tr>                              <td>Reading</td>                              <td>900</td>                          </tr>                          <tr>                              <td>Math</td>                              <td>700</td>                          </tr>                          <tr>                              <td>Writing</td>                              <td>800</td>                          </tr>                          <tr>                              <td><strong>Total</strong></td>                              <td><strong>2,400</strong></td>                          </tr>                          </tbody>  

This is what my Grade.rb model looks like:

# == Schema Information  #  # Table name: grades  #  #  id         :integer          not null, primary key  #  subject    :string  #  result     :string  #  grade_type :integer  #  profile_id :integer  #  created_at :datetime         not null  #  updated_at :datetime         not null  #    class Grade < ActiveRecord::Base    belongs_to :profile      enum grade_type: { csec: 0, cape: 1, sat: 2, g7: 3, g8: 4, g9: 5, g10: 6, g11: 7, g12: 8, g13: 9 }  end  

This is what that table looks like currently, i.e. before using the lookup_context method in Rails:

<table class="table table-hover table-bordered">                      <thead>                      <td colspan="2" class="text-center">                        <strong>SAT</strong>                      </td>                      <tr>                          <th>Subject</th>                          <th>Grade</th>                      </tr>                      </thead>                      <tbody>                        <% @sat_grades.each do |grade| %>                        <tr>                          <% if grade.subject.eql? "Total" %>                            <td><strong><%= grade.subject %></strong></td>                            <td><strong><%= grade.result %></strong></td>                          <% else %>                            <td><%= grade.subject %></td>                            <td><%= grade.result %></td>                          <% end %>                        </tr>                        <% end %>                      </tbody>  

Where @sat_grades is this: @sat_grades = @profile.grades.where(grade_type: :sat).

I want to use this lookup_context method, I was thinking like this:

 <% @grades.each do |grade| %>     <% if lookup_context.template_exists?(grade.grade_type, "grades/grade_types", true) %>         <%= render partial: "grade/grade_types/#{grade.grade_type}", locals: {event: event, index: index} %>     <% end %>    <% end %>  

The issue I am running into is that each grade_type has a different table. So grade_type: :sat belongs in the "SAT" table, the same for "CSEC", "g11", etc.

I can't think of a way to have each of those grade_types rendered specifically within their HTML table, without having lots of lookup_context.template_exists? calls within that view.

It almost defeats the purpose of doing it like that, if I have to have a lookup_context call for each grade_type.

What's the best way to approach this so I just have 1 lookup_context call (if possible), but it correctly renders and handles all the different grades correctly.

Can't install sqlite

Posted: 17 Sep 2016 06:01 AM PDT

I use mac.

Gem version: 2.4.5.1 Ruby version: ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin15] Gemfile:

source 'https://rubygems.org'    gem 'rails', '3.2.3'    group :development do      gem 'sqlite3', '1.3.5'  end    # Gems used only for assets and not required  # in production environments by default.  group :assets do    gem 'sass-rails',   '3.2.4'    gem 'coffee-rails', '3.2.2'      gem 'uglifier', '1.2.3'  end    gem 'jquery-rails', '2.0.1'    group :production do      gem 'pg', '0.12.2'  end  

I spent about 3 hours searching a solution, without luck.

I read 'Ruby on Rails Tutorial' by Michael Hartl, on page 46.

First one error that leads to another, that leads to another...

It starts with this command:

bundle install --without production  

That results in this error:

    Fetching gem metadata from https://rubygems.org/..........  Fetching version metadata from https://rubygems.org/..  Fetching dependency metadata from https://rubygems.org/.  Resolving dependencies...  Using rake 11.2.2  Using i18n 0.7.0  Using multi_json 1.12.1  Using builder 3.0.4 (was 3.2.2)  Using erubis 2.7.0  Using journey 1.0.4  Using rack 1.4.7 (was 2.0.1)  Using hike 1.2.3  Using tilt 1.4.1 (was 2.0.5)  Using mime-types 1.25.1 (was 3.1)  Using polyglot 0.3.5  Using arel 3.0.3 (was 7.1.2)  Using tzinfo 0.3.51 (was 1.2.2)  Using bundler 1.13.1  Using coffee-script-source 1.10.0  Using execjs 2.7.0  Using json 1.8.3  Using thor 0.14.6 (was 0.19.1)  Using sass 3.4.22  Installing sqlite3 1.3.5 (was 1.3.11) with native extensions  Using activesupport 3.2.3 (was 5.0.0.1)  Using rack-cache 1.6.1  Using rack-test 0.6.3  Using rack-ssl 1.3.4  Using sprockets 2.1.4 (was 3.7.0)  Using treetop 1.4.15  Using coffee-script 2.4.1  Using uglifier 1.2.3 (was 3.0.2)  Using rdoc 3.12.2  Gem::Ext::BuildError: ERROR: Failed to build gem native extension.    /Users/Money/.rbenv/versions/2.2.3/bin/ruby -r ./siteconf20160917-4100-9i5b1f.rb  extconf.rb  checking for sqlite3.h... yes  checking for sqlite3_libversion_number() in -lsqlite3... yes  checking for rb_proc_arity()... yes  checking for sqlite3_initialize()... yes  checking for sqlite3_backup_init()... yes  checking for sqlite3_column_database_name()... no  checking for sqlite3_enable_load_extension()... no  checking for sqlite3_load_extension()... no  creating Makefile    make "DESTDIR=" clean    make "DESTDIR="  compiling backup.c  compiling database.c  compiling exception.c  compiling sqlite3.c  compiling statement.c  statement.c:258:11: warning: implicit declaration of function 'RBIGNUM' is invalid in  C99 [-Wimplicit-function-declaration]        if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {            ^  ./sqlite3_ruby.h:16:24: note: expanded from macro 'RBIGNUM_LEN'  #define RBIGNUM_LEN(x) RBIGNUM(x)->len                         ^  statement.c:258:11: error: member reference type 'int' is not a pointer        if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {            ^~~~~~~~~~~~~~~~~~  ./sqlite3_ruby.h:16:36: note: expanded from macro 'RBIGNUM_LEN'  #define RBIGNUM_LEN(x) RBIGNUM(x)->len                         ~~~~~~~~~~  ^  statement.c:258:32: error: use of undeclared identifier 'SIZEOF_BDIGITS'        if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {                                 ^  1 warning and 2 errors generated.  make: *** [statement.o] Error 1    make failed, exit code 2    Gem files will remain installed in  /Users/Money/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/sqlite3-1.3.5 for  inspection.  Results logged to  /Users/Money/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-15/2.2.0-static/sqlite3-1.3.5/gem_make.out    An error occurred while installing sqlite3 (1.3.5), and Bundler cannot  continue.  Make sure that `gem install sqlite3 -v '1.3.5'` succeeds before bundling.  

Then, because of the last phrase " Make sure that gem install sqlite3 -v '1.3.5' succeeds before bundling. ", I run that command:

gem install sqlite3 -v '1.3.5'  

And get this error which I have no clue what to do about:

    Building native extensions.  This could take a while...  ERROR:  Error installing sqlite3:      ERROR: Failed to build gem native extension.        /Users/Money/.rbenv/versions/2.2.3/bin/ruby -r ./siteconf20160917-4314-20lcl4.rb extconf.rb  checking for sqlite3.h... yes  checking for sqlite3_libversion_number() in -lsqlite3... yes  checking for rb_proc_arity()... yes  checking for sqlite3_initialize()... yes  checking for sqlite3_backup_init()... yes  checking for sqlite3_column_database_name()... no  checking for sqlite3_enable_load_extension()... no  checking for sqlite3_load_extension()... no  creating Makefile    make "DESTDIR=" clean    make "DESTDIR="  compiling backup.c  compiling database.c  compiling exception.c  compiling sqlite3.c  compiling statement.c  statement.c:258:11: warning: implicit declaration of function 'RBIGNUM' is invalid in C99 [-Wimplicit-function-declaration]        if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {            ^  ./sqlite3_ruby.h:16:24: note: expanded from macro 'RBIGNUM_LEN'  #define RBIGNUM_LEN(x) RBIGNUM(x)->len                         ^  statement.c:258:11: error: member reference type 'int' is not a pointer        if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {            ^~~~~~~~~~~~~~~~~~  ./sqlite3_ruby.h:16:36: note: expanded from macro 'RBIGNUM_LEN'  #define RBIGNUM_LEN(x) RBIGNUM(x)->len                         ~~~~~~~~~~  ^  statement.c:258:32: error: use of undeclared identifier 'SIZEOF_BDIGITS'        if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {                                 ^  1 warning and 2 errors generated.  make: *** [statement.o] Error 1    make failed, exit code 2    Gem files will remain installed in /Users/Money/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/sqlite3-1.3.5 for inspection.  Results logged to /Users/Money/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-15/2.2.0-static/sqlite3-1.3.5/gem_make.out  Jonass-MBP:demo_app Money$   

I tried the suggestions on this thread, but all suggestions return with "Command not found".

I tried to run gem install sqlite3-ruby as well, as suggested in this thread, didn't work.

I tried to run gem sources --add http://rubygems.org/, as suggested in this thread, in case the failure had something to do with HTTPS or HTTP, didn't work.

Any suggestions?

Thank you! Jonas

ActiveRecord many-to-many table with association type field - Rails

Posted: 17 Sep 2016 06:25 AM PDT

I'm building a Rails photo gallery app which allows users to create private galleries and invite users to the gallery under different permissions (i.e: viewer and editor).

I am thinking that galleries_users table will be required to resolve the many-to-many relationsip:

user_id | gallery_id  --------------------  1       | 4  --------------------  2       | 4  

But should I store the association permission type? Can I just add a permission field:

user_id | gallery_id | permission  ---------------------------------  1       | 4          | edit  ---------------------------------  2       | 4          | view  

Is this on the right track?

I have also seen the Rolify gem but using that would mean adding a user to a project (via method above) and the adding a role separately through Rolify's interface. Unless there is a way I can skip the first step of adding a user to a gallery and treat the role as the association?

How to reverse a SUDO fix/ restore old file plan?

Posted: 17 Sep 2016 04:48 AM PDT

In trying to resolve this issue (which popped up out of nowhere and for which there were no obvious problems with capital letters):

Strange error in rails - missing helper

I (foolishly, I know) made use of one of the suggested solutions in the comments:

I had the same problem, but NO user-created directories that had uppercase letter in them... only /Users.

I tried upgrading to ruby 2.2.1 - this did not fix it.

I very hesitantly fixed it by doing the same case-sensitive "fix" on my /Users directory:

 cd /     sudo mv Users users1     sudo mv users1 users  

I have yet to see if that breaks anything else....

For me, it has broken everything else. I now appear to have a 'Users/users1/derekbreslin' folder, where all my data is held (and which I appear unable to access through the terminal). This is in addition to a 'Users/derekbreslin' folder, which I assume is my original folder, but which is now essentially empty. My machine doesn't boot up as it used to either - I can use it, but the desktop is entirely clear and the machine thinks I'm opening most applications up for the first time now.

More than anything, I'd like to just get my machine back to where it was - sadly I don't have time machine switched on for my Mac (I didn't realise you needed to..), so I'm casting around for help.

In short, is there a way, perhaps using the terminal, to reverse the instructions above (and therefore the foolish damage that I've done)? All advice will be very gladly received!

And apologies if this is the wrong place for such a request - more than happy to direct it elsewhere if need be.

Rails custom position of results from database

Posted: 17 Sep 2016 04:48 AM PDT

I'm writing small forum engine in Rails 5 and I'm at the part of creating new categories and forums; is it possible to implement system which will allow me to show categories / forums right before / after defined ones (like in phpBB) and how could I do that?

Example (categories#new) :

  • name of category
  • description of category
  • position of category

I want to save that position and based on it show results from database.

Why does Rspec ignore default_url_options that I set in application_controller.rb

Posted: 17 Sep 2016 04:46 AM PDT

I've overridden method default_url_options in application.rb

class ApplicationController < ActionController::Base    protect_from_forgery with: :exception    before_action :set_locale      def redirect_to_root      redirect_to root_path    end      private        def default_url_options(options={})        { locale: I18n.locale }.merge options      end        def set_locale        if params[:locale].blank?          logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"          abbr = extract_locale_from_accept_language_header          I18n.locale = if Language.find_by(abbr: abbr).nil?                          logger.debug "* Unknown Language"                          I18n.default_locale                        else                          abbr                        end          logger.debug "* Locale set to '#{I18n.locale}'"        else          I18n.locale = params[:locale]        end      end        def extract_locale_from_accept_language_header        request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first      end  end  

It works good. But when I start controller tests they all fail. For example:

it "renders show template" do    get :show, id: @book.id    expect(response).to render_template :show  end    ActionController::UrlGenerationError:  no route matches {:action=>"show", :controller=>"books", :id=>"1"}  

Why does rspec not pass defautl url option (locale) that I set in ApplicationController?And how can tell rspec to do this?

Rails+Devise password reset token expires before the configured time period

Posted: 17 Sep 2016 06:11 AM PDT

Rails Version: 5.0.0.1  Devise Version: 4.2  

In my devise.rb file I define lifetime for password token to be 6 hours

  # Time interval you can reset your password with a reset password key.    # Don't put a too small interval or your users won't have the time to    # change their passwords.    config.reset_password_within = 6.hours  

When I opt for password reset through the Forgot Password link, I can see the timestamp and token generated

postgres=> select reset_password_token, reset_password_sent_at from users where email='email@gmail.com';                         reset_password_token                       |   reset_password_sent_at  ------------------------------------------------------------------+----------------------------   89f51bce1bc6b495c16a50b015d03897d0520a8b58c300a5deef16b2c45cac82 | 2016-09-16 21:18:01.322362  

Active record and application timezone are both set to 'Asia/Kolkata' but when I click on the link delivered in email and try changing password (which is within minutes of the email delivered) the password change fails with message

Reset password token has expired, please request a new one

I have recoverable enabled in the user model, but to no use here.

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

shopify handle app install hook/event

Posted: 17 Sep 2016 04:11 AM PDT

I have shopify rails app using official gem, I want to handle app install event, is there any hook for this or how i can override controller?

Can't verify CSRF token authenticity! RAILS API with POST

Posted: 17 Sep 2016 06:07 AM PDT

I trying post a json file with Rails API. I have try to fix but can't run This my problem:

Sever log:

Started POST "/students/" for 127.0.0.1 at 2016-09-17 17:45:33 +0700    ActiveRecord::SchemaMigration Load (0.0ms)  SELECT "schema_migrations".* FROM "schema_migrations"  Processing by Devise::RegistrationsController#create as */*    Parameters: {"student"=>{"name"=>"Duong", "score"=>"10"}, "registration"=>{"student"=>{"name"=>"Duong", "score"=>"10"}}}  Can't verify CSRF token authenticity.  Unpermitted parameters: name, score     (0.0ms)  begin transaction     (0.0ms)  rollback transaction    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/devise-4.2.0/app/views/devise/registrations/new.html.erb within layouts/application    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/devise-4.2.0/app/views/devise/shared/_links.html.erb (10.0ms)    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/devise-4.2.0/app/views/devise/registrations/new.html.erb within layouts/application (60.0ms)  Completed 500 Internal Server Error in 442ms (ActiveRecord: 0.0ms)  

Student.rb

This is my student model

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

Application_controller

I have fix excetion => null_session

class ApplicationController < ActionController::Base      protect_from_forgery with: :null_session    end  

Student_controller

class Api::StudentsController < ApplicationController    def index      students = Student.all      render json: students, status: 200    end    def show      response_with Student.find(params[:id])    end    def create      student = Student.new(student_params)      #if you save successfully than response with json data and status code 201      if student.save        render json: user, status: 201, location: student      else        render json: {error: user.errors}, status: 422      end    end    private    def student_params      params.require(:student).permit(:name, :score)    end  end  

router.rb

Rails.application.routes.draw do    devise_for :students    namespace :api, path: '/',constraints: {subdomain: 'api'} do      resources :students, only: [:index, :show, :create]    end  end  

But, when I send a post to api.1312100.com/students/

{"student": {"name": "Duong", "score": "10"}}  

have a error:

500 internal server error  

Validate unique field in Rails app

Posted: 17 Sep 2016 03:50 AM PDT

In my Rails app, I've got two models - User and Account.

A User can have many Accounts.

An Account includes a name field as shown in the schema below.

How can I validate that the name field is unique for an Account but not necessarily unique in the database? For example, User1 could have an Account with the name Cash and User2 could have a different Account but with the same name Cash.

user.rb:

class User < ActiveRecord::Base    has_many :accounts      before_save { self.email = email.downcase }      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i      validates :email, presence: true,                      length: { maximum: 255 },                      format: { with: VALID_EMAIL_REGEX },                      uniqueness: { case_sensitive: false }      has_secure_password      validates :password, presence: true, length: { minimum: 6 }      # Returns the hash digest of the given string.    def User.digest(string)      cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :                                                    BCrypt::Engine.cost      BCrypt::Password.create(string, cost: cost)    end  end  

account.rb:

class Account < ActiveRecord::Base    belongs_to :user    has_many :balances      before_save { self.active = true }      validates :name, presence: true, length: { maximum: 250 },                    uniqueness: { case_sensitive: false }      validates :user, presence: true  end  

schema.rb:

  ....    create_table "accounts", force: :cascade do |t|      t.string   "name"      t.boolean  "credit"      t.boolean  "active",     default: true, null: false      t.datetime "created_at",                null: false      t.datetime "updated_at",                null: false      t.integer  "user_id"    end      create_table "balances", force: :cascade do |t|      t.decimal  "balance"      t.date     "date"      t.integer  "account_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "users", force: :cascade do |t|      t.string   "email"      t.boolean  "admin"      t.datetime "created_at",      null: false      t.datetime "updated_at",      null: false      t.string   "password_digest"    end      add_index "users", ["email"], name: "index_users_on_email", unique: true    ....  

Полиморфная связь rails [on hold]

Posted: 17 Sep 2016 03:21 AM PDT

Здравствуйте, нужно что б моя модель Comment хранила account_id который будет получать из form_for [@account, @account.comments.build] т.е. из конкретного аккаунта, и user_id который будет получать из current_user.id (devise). Подскажите какую связь поставить и как настроить форму и контроллер Что б обьект Comment сохранял 2 параметра: user_id и account_id.

Rails 5: rails db:migrate or rake db:migrate in heroku?

Posted: 17 Sep 2016 03:30 AM PDT

since the release of rails 5.0 it is suggested to use rails db:migrate
My question is, when using heroku, which one should I use:
heroku run rails db:migrate or heroku run rake db:migrate ?

Custom actions using devise

Posted: 17 Sep 2016 03:39 AM PDT

Background:

The Rails 4 application I am working on has differing logic for API and web registrations, and part of this logic makes their integration extremely difficult. To that end, I'm attempting to separate the routes to deal with issues arising from inheritance, new reCAPTCHA gem, and new logic. (both actions call registrations#create after their respective logic.) I've solved most of the issues arising from separating these two; however, getting the routes working has proven difficult as well.

I'd greatly appreciate any help!


Desired Result:

I'm trying to define a route to a custom action using Devise, and prevent it from creating the default route as well. I've gotten one of them working, but not the second. Here's the excerpt from my routes.rb:

Registry::Application.routes.draw do    devise_for :users,               controllers: {                 passwords:     'users/passwords',                 sessions:      'users/sessions',                 registrations: 'users/registrations'               }      devise_scope :user_registration do      post 'users', to: 'users/registrations#custom_one'    end      # ...      namespace :api do      namespace :v1 do        # ...        devise_scope :user do          post 'users', to: 'registrations#custom_two'        end      end    end  end  

Issues:

The issue is that this code generates two nearly-identical routes. Excerpt from rake routes:

user_registration POST   /users(.:format)         users/registrations#create              users POST   /users(.:format)         users/registrations#custom_one       api_v1_users POST   /api/v1/users(.:format)  api/v1/registrations#custom_two  

I also want the custom route to have the correct prefix/route name (user_registration), though I've been unable to do this.

I've found plenty of documentation on custom names for Devise routes, but not for custom actions. Especially not when using devise_for.


To summarize:

  • I need to disable the default users/registrations#create route
  • and specify a route to a custom action (users/registrations#custom_one)
  • with the correct prefix/name (user_registration)

hopefully as elegantly as possible, as I would rather avoid specifying each route independently.

Is there a way to get File System root path in ruby?

Posted: 17 Sep 2016 04:28 AM PDT

I am making an education website which should display host file system. Is there a way to get Operating System (or File System, I don't know exactly how it's called) root path?

sharetribe homepage error after login in sharetribe

Posted: 17 Sep 2016 01:58 AM PDT

After login with http://52.27.73.120:3000/ in sharetribe. I getting the errors. It is also mentioned that this is fresh installation of sharetribe. But i am getting errors after login in the system. If someone help me to figure out the issue. I will be greatful. Thanks in advance.

No such file or directory @ rb_file_s_mtime - app/assets/webpack/server-bundle.js  

enter image description here

What is socket hijacking?

Posted: 17 Sep 2016 03:07 AM PDT

I'm reading a great post on Rails 5 actioncable introduction. There it says: "Action Cable uses the Rack socket hijacking API to take over control of connections from the application server. ". What does the "socket hijacking" mean?

How to convert a multi-key hash to single key hash in Ruby for Highcharts

Posted: 17 Sep 2016 03:30 AM PDT

I have this data in Ruby, for creating a barchart using Highcharts.js which requires the data in a JSON format:

data = {["January", "a"]=>54, ["January", "b"]=>13, ["January", "d"]=>2, ["January", "c"]=>1,           ["February", "a"]=>27, ["February", "b"]=>11, ["February", "c"]=>4, ["March", "a"]=>22,           ["March", "b"]=>11, ["March", "d"]=>2, ["March", "c"]=>2, ["April", "a"]=>32,           ["April", "b"]=>12, ["April", "d"]=>6, ["April", "c"]=>2, ["May", "a"]=>7,           ["May", "d"]=>3, ["June", "a"]=>5, ["July", "a"]=>25,           ["August", "a"]=>23, ["August", "d"]=>3, ["August", "c"]=>3, ["September", "a"]=>6}  

The data is stored in a variable and is not coming from a file.

I want to convert this into a json object to send it to Highcharts for charting. I need the data in the following format:

category = ["January","February","March","April","May","June","July","August","September"]    series: [{              name: 'a',              data: [54, 27, 22, 32, 7, 5, 25, 23, 6]          }, {              name: 'b',              data: [13, 11, 11, 12, 6, 0, 0, 0, 6]          }, {              name: 'c',              data: [1, 4, 0, 2, 0, 0, 0, 3, 6]          },              {              name: 'd',              data: [2, 0, 0, 6, 3, 0, 0, 3, 6]          }]  

The data is missing for some months, and sometimes not in alphabetical order.

Is there an easy way in Ruby to unlist the original Hash, and then extract the information out of it while filling the missing values with 0, and getting the JSON output as required?

p.s. :Tried converting the data.to_json but highcharts doesnt accept it in raw form. Is there any other way to create a bar chart using this data in Highcharts?

Capistrano doesn't create puma.pid file

Posted: 17 Sep 2016 02:49 AM PDT

I use Capistrano to deploy my Rails app. However, when I deploy my application, puma.pid file is not being created, which leads to a problem - I can't restart server or deploy new version with capistrano - capistrano fails to stop puma, because puma.pid don't exests and it assumes no puma processes is running. And I get ADDRESS ALREADY IN USE error when capistrano tries to run another version of puma.

Here is my deploy.rb

lock '3.4.0'    set :application, 'appname'  set :repo_url, 'giturl'  set :deploy_to, '/home/user/appname'  set :pty, false  set :linked_files, %w(config/application.yml config/database.yml)  set :linked_dirs, %w(log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/uploads)  set :keep_releases, 5  set :rvm_type, :user  set :rvm_ruby_version, '2.3.0'    set :puma_rackup, -> { File.join(current_path, 'config.ru') }  set :puma_state, "#{shared_path}/tmp/pids/puma.state"  set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"  set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock" # accept array for multi-bind  set :puma_conf, "#{shared_path}/config/puma.rb"  set :puma_access_log, "#{shared_path}/log/puma_error.log"  set :puma_error_log, "#{shared_path}/log/puma_access.log"  set :puma_role, :app  set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production'))  set :puma_threads, 1  set :puma_workers, 1  set :puma_worker_timeout, nil  set :puma_init_active_record, true  set :puma_preload_app, true    set :sidekiq_config, 'config/sidekiq.yml'  set :sidekiq_log, '/dev/null'  set :sidekiq_processes, 1    set :clockwork_file, "clock.rb"    namespace :deploy do      desc 'Recompile all enterprise themes'    task :recompile_themes, [:command] => 'deploy:set_rails_env' do |task, args|      on primary(:app) do        within current_path do          with :rails_env => fetch(:rails_env) do            rake 'themes:recompile'          end        end      end    end      after :finishing, "deploy:recompile_themes"  end    require 'appsignal/capistrano'  

And when I try to stop running Puma, for example, I get the following error:

...  DEBUG [37113fcf] Running [ -f /home/user/appname/shared/tmp/pids/puma.pid ] as user@server  DEBUG [37113fcf] Command: [ -f /home/user/appname/shared/tmp/pids/puma.pid ]  DEBUG [37113fcf] Finished in 0.273 seconds with exit status 1 (failed).  WARN Puma not running  

And indeed, /home/user/appname/shared/tmp/pids/puma.pid file don't exists. Do I need to create it manually or something? sidekiq.pid that is also being created the same way can be found in the same directory, so I don't think it's a permissions issue.

Any advices on how to approach this?

PATH set to RVM ruby but GEM_HOME and/or GEM_PATH not set

Posted: 17 Sep 2016 12:49 AM PDT

Full error message:

Warning: PATH set to RVM ruby but GEM_HOME and/or GEM_PATH not set, see: https://github.com/rvm/rvm/issues/3212

I found many articles on the subject, but I don't know what to do.

My .zshrc:

export PATH="$PATH:$HOME/.rvm/bin" # Add RVM to PATH for scripting  export PATH=/home/dartnyan/.rvm/gems/ruby 2.3.0/bin:/home/dartnyan/.rvm/gems/ruby-2.3.0@global/bin:/home/dartnyan/.rvm/rubies/ruby-2.3.0/bin:/usr/local/heroku/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/ usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/dartnyan/.rvm/bin:/snap/bin:/home/dartnyan/.rvm/bin:/home/dartnyan/.rvm/bin:/home/dartnyan/.vimpkg/bin      dartnyan@PC:~$ echo $PATH  /home/dartnyan/.rvm/gems/ruby-2.3.0/bin:/home/dartnyan/.rvm/gems/ruby-2.3.0@global/bin:/home/dartnyan/.rvm/rubies/ruby-2.3.0/bin:/usr/local/heroku/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/dartnyan/.rvm/bin:/snap/bin:/home/dartnyan/.rvm/bin:/home/dartnyan/.rvm/bin:/home/dartnyan/.vimpkg/bin  

Encrypt String to database and file saved

Posted: 17 Sep 2016 01:00 AM PDT

Guess I'm digging around the internet to learn about security and how to explain to users that their information is kept safe; we all know nothing is safe.

I use an API that needs a consumer key/secret and a privatekey.pem file, in total three "items". These are the two questions:

  1. How to store these consumer keys on a postgres db?
  2. Where to upload a privatekey.pem file?

For number 2, I've been reading here. I could not ask question there as this relates to Ruby on Rails; I am using Ruby on Rails 5 here. Could I simply store the consumer keys as normal sting type in the database and use Paperclip to upload to aws (encrypted)?

These consumer key/secret and .pem file are from users.

I think I may need to "password-save" those consumer strings.

Query returns record in Rails console but Model resulting in 500 Internal Server Error

Posted: 17 Sep 2016 05:28 AM PDT

Context - I am creating a quiz app to learn rails. A particular view displays list of questions and radio buttons. User has to select option for each question and click submit button. Submit button invokes an AJAX call and calls controller.

Issue - In Controller, the query returns

Completed 500 Internal Server Error in 7ms (ActiveRecord: 0.2ms)

However when I run the same query in Rails console, I get a proper result.

Log Output -

Question Load (0.2ms) SELECT "questions".* FROM "questions" WHERE "questions"."id" = ? LIMIT 1 [["id", 29]]

Completed 500 Internal Server Error in 7ms (ActiveRecord: 0.2ms)

Rails Console Output -

Question Load (0.6ms) SELECT "questions".* FROM "questions" WHERE "questions"."id" = ? LIMIT 1 [["id", 29]] => # irb(main):017:0>

Model

class Question < ActiveRecord::Base    belongs_to :title  end  

Table Schema

create_table "questions", force: :cascade do |t|    t.string   "question"    t.string   "option1"    t.string   "option2"    t.string   "option3"    t.string   "option4"    t.string   "answer"    t.datetime "created_at", null: false    t.datetime "updated_at", null: false    t.integer  "title_id"  end  

Controller

  def check_answers      answers = params[:answers]      @response = []      my_hash = {}      answers.each_key do |key|        question_id = answers[key]['question_id']        user_answer = answers[key]['user_answer']        correct_answer = Question.find_by id: question_id        correct_answer_jk = correct_answer[0]['answer']        my_hash['question_id'] = question_id        my_hash['user_answer'] = user_answer        if user_answer == correct_answer_jk          my_hash['response'] = 'Correct'          my_hash['correct_answer'] = ''        else          my_hash['response'] = 'Incorrect'          my_hash['correct_asnwer'] = correct_answer_jk        end        @response.push(my_hash)      end      respond_to do |format|        format.js        format.html      end    end  

I have googled the issue, but I am not getting any pointers to solve the issue. Please note I am using Sqlite.

Rails 4 many-to-many querying both ways

Posted: 17 Sep 2016 06:06 AM PDT

I have a many-to-many relationship between two models - Teams and Tournaments.

When I query to get teams participation in a tournament by calling @tournament.teams i get the expected results.

When I'm trying it the other way around by calling @team.tournaments, to get a list of tournaments in which the team is participation I'm getting the following error:

Mysql2::Error: Unknown column 'tournaments.team_id' in 'where clause': SELECT `tournaments`.* FROM `tournaments` WHERE `tournaments`.`team_id` = 2  

How can I make this work? I suppose it's a simple fix, but I'm just a beginner and can't seem to figure it out myself.

EDIT:

Team model:

class Team < ActiveRecord::Base    has_many :user_teams    has_many :users, :through => :user_teams      has_many :teams_in_tournaments    has_many :tournaments, :through => :teams_in_tournaments    has_many :tournaments      belongs_to :team_leader, class_name: "User"    has_many :matches  end  

Tournament model:

class Tournament < ActiveRecord::Base    has_many :teams_in_tournaments    has_many :teams, :through => :teams_in_tournaments    belongs_to :organizer, class_name: "User"    has_one :rule, :dependent => :destroy    accepts_nested_attributes_for :rule    has_many :matches, :dependent => :destroy    belongs_to :winner, class_name: "Team"  end  

Rails: How to filter table records during a period?

Posted: 16 Sep 2016 11:54 PM PDT

model Express has an attribute "date"
In the Index page, I hope to filter out express information during a period, what technology can be used here?

I searched railscast 240 "Search, Sort, Paginate with AJAX", but it did cover this.

what I want basically like this. When the first time index page is loaded no record shows,until I set a period and click search button it will show records.

enter image description here

Unable to set cookies in rails [duplicate]

Posted: 16 Sep 2016 09:25 PM PDT

This question is an exact duplicate of:

LoginController:

class LoginController < ApplicationController  def new      cookies[:time]=Time.now      render "login"  end    def auth      if params[:name].present? && params[:pass].present?           @name=params[:name]          pass=params[:pass]            if( @name == "admin" && pass == "admin" )              cookies[:time] = Time.now              render "success"          else              render "authfailed"          end      else          render "argerror"      end  end  end  

login.html.erb:

<body>      <center>      <h1> Login </h1>      <form action='login/auth' method='POST'>          Name: <input type="text" name="name" width=20><br>          Password: <input type="password" name="pass" width=20><br>          <input type="submit" value="submit">      </form>      </center>      <br><br>  </body>  

In the above scenario, the cookies stored in auth action is not set in client browser. To check that what I do is, when the user calls "login/new", then the login page is rendered to the browser. So, at that time I set the cookie. Here it is properly worked. But when the user submitted the entered data to "login/auth" action, it is not worked. I need to set the cookie only when the username and password is "admin". So I set the cookie within "if" condition. But it is not worked. But it successfully renders the "success.html.erb" page. So why the cookies is not set in "success.html.erb" page. Is there any error in my code ?

Understanding Security and Secret Keys

Posted: 16 Sep 2016 09:37 PM PDT

I am making a Rails application and am trying to understand security as it involves secret keys.

My project uses Rails 5 and the Devise gem.

I read in several places that you don't want to put files like secrets.yml onto github for security reasons (which I discovered several commits down the road). However, my secret keys that are used in production are environment variables (although my development and keys are not, they can be seen).

What I am trying to figure out now, is that is it fine that files like secrets.yml (I also heard some things about database.yml as well), have ended up on github, as long as the important bits (like secret keys) are environment variables, which fortunately Rails seems to have thought of by default? Or should I go through the effort of removing those files?

Trying to integrate Elm with out legacy Rails 3 app but I keep seeing Elm not defined in Chrome console

Posted: 16 Sep 2016 09:08 PM PDT

I use brunch and the final .js I got doesn't have things like var _user$project$MainApp$getPosition = function (_p0) {

Why can't I query my ActiveRecord CollectionProxy?

Posted: 16 Sep 2016 08:16 PM PDT

I have a form object that builds nested children

@billing_items = build_billing_items    def build_billing_items    @billable_items.each do |item|      @billing.billing_items.find_or_initialize_by(item_id: item.id).tap do |billing_item|        billing_item.amount = item.amount      end    end    @billing.billing_items  end  

Then in my attribute writer I try to find or initialize my child records vs my form params..

def billing_items_attributes=(params)    params.each do |_i, hash|      @billing_items.find_or_initialize_by(item_id: hash[:item_id].to_i).tap do |b|        b.amount = hash[:amount]      end    end  end  

At this point I could not use find_or_initialize on @billing_items. I did some tinkering an found out that @billing_items at this point is of type ActiveRecord_Associations_CollectionProxy which does not have query methods where or find_by.

Is there another more ActiveRecord way to query @billing_items other than using the ruby detect or select? Is there a way for me to avoid ending up with an ActiveRecord_Associations_CollectionProxy? Or from a form object perspective, can I do something better to avoid having to find_or_initialize_by in my attribute writer?

No comments:

Post a Comment