Wednesday, December 14, 2016

Ruby On Rails help on Paper_trail gem | Fixed issues

Ruby On Rails help on Paper_trail gem | Fixed issues


Ruby On Rails help on Paper_trail gem

Posted: 14 Dec 2016 07:55 AM PST

So I have a project with authentication of users, and history tracking of some models. For the history I use the paper_trail gem, I have a problem of filtering the history to show to the user, I have configured it to track the current_user id into the Whodunnit field. My user has role_id which specifies the role from the Roles table Also i have another table with some items that have id and user_id fields. And now my problem is how to take specific rows from Versions table according to the role of the user, like for ex: if user role is 'SomeRole' it has to return only those actions done by the users that have the same role 'SomeRole'. I know that i can take out all the actions by

@versions = PaperTrail::Version.order('created_at')  

but have no idea on how to filter to select only those that are satisfying for my uses. Is there an easy way to do it or should i hardcode it like selecting one by one, than check all user_id of their roles and so on so forth? Hope you understood my messy way of explaining

Seamless staging experience on production app

Posted: 14 Dec 2016 07:54 AM PST

Problem

My ios app uses webview but I want to support a staging server for all internal people. The issue is that I don't want to have two apps on the app store. Also, I don't want to have to have to manually release a second app using testflight because I want internal peoples spouses and family members to be using staging.

Idea

So instead, I wanted to make it that if you try and log into production app but the credentials are not in the db, then it will query the staging app and if the credentials are in that db, it will log you in to staging and redirect you to the staging url. How can this be done securely? Currently, I am using the Devise gem for authentication purposes.

Hypothesis - These are the steps I hypothesize make sense

  1. query staging for credentials
  2. create cookie on production
  3. send cookie to staging
  4. forward user to staging

Is this the best way of solving my problem? How do I implement this using Devise? Are there any gems out there that I should know about?

simple_form validation message for a field not in database

Posted: 14 Dec 2016 07:57 AM PST

class Customer < ApplicationRecord     attr_accessor :date     validates_presence_of :name, :principalAmount,:interestRate,:accountType,:duration,:date  end  

Except date all are there in my customers table. I am using simple_form for getting those values. But problem is that there is no validation happening for :date.For others it displays message if the field is empty. How do I display presence_of validation message in simple_form for :date. I am using bootstrap datepicker.

  <%= simple_form_for @customer do |f| %>            <%= f.input :name,:autocomplete => :off %>            <%= f.input :principalAmount,:autocomplete => :off %>            <%= f.input :interestRate %>            <%= f.input :accountType %>            <%= f.input :duration,:autocomplete => :off %>            <%= f.text_field :date, "data-provide" => 'datepicker',"data-date-format"=>"dd-mm-yyyy" %>            <%= f.button :submit %>          <% end %>  

Environment variables for Paperclip

Posted: 14 Dec 2016 08:03 AM PST

I am following this guide to get model attachments stored in S3. I am curious as to why the AWS key and secret and bucket name need to be stored in config/environments/production.rb AS WELL AS set using

heroku config:set AWS_ACCESS_KEY_ID=your_access_key_id  

I thought it would be one or the other. For obvious reasons, I would rather not store the key and secret in a file in a repo.

Array iteration in rails controller: it only puts the last value

Posted: 14 Dec 2016 07:53 AM PST

I have to iterate on array in my rails controller but it only returns the last value of it:

array = ["a", "b", "c"]     array.each do |arr|     @arry = arr   end  

@arry gives me "c" but I want it to give me a b c

So, when I add a API method in the each iteration, it only gives me a result for the "c" value but I want a result for all of them.

FYI: when I iterate this array in my view, everything works

Ruby On Rails - Image uploaded by User will not display

Posted: 14 Dec 2016 07:40 AM PST

I am making a blog application but when I create a post where the user has uploaded an image it doesn't display the image.

I have the carrierwave gem and I have added :image to post_paramas in the post controller.

Post show view

<p>  <strong>Image:</strong>      <div class="images">  <%= image_tag @post.image_url%>  </div>  </p>  

IMage_uploader

 storage :file    def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end      def extension_white_list      %w(jpg jpeg gif png)    end  

Post _form

   <div>      <%= form_for(@post, hmtl: { multipart: true } ) do |f| %>      <%= f.label :image %>      <%= f.file_field :image %>    </div>  

I'm trying to do it without magick because it didn't work when I tried that it kept saying magick wasn't installed even though it was.

How can I ignore many endpoints in Skylight?

Posted: 14 Dec 2016 07:37 AM PST

Skylight allows you to ignore a list of endpoints by specifying them in your skylight.yml (see Ignoring heartbeat endpoints). But this list doesn't support wildcards and I have a lot of endpoints I want to ignore-- what should I do?

Using Carrierwave, how can I make sure the remote url is valid picture before trying to save it to the record?

Posted: 14 Dec 2016 07:39 AM PST

I was attempting to save my picture files in the following manner in my ActiveJob, but a lot of my records were showing up as invalid. After looking into why, it appears the remote url isn't finding a valid picture and is returning a 404 error message. How can I change my current setup to (1) attempt to get the picture, (2) if it's an invalid link then ignore it and still save the record -- just without the picture?

My current setup...

if self.headshot_url.present?     player_record.remote_headshot_image_url = self.headshot_url     if !player_record.valid?       player_record.remote_headshot_image_url = nil     end  end  

Unable to generate the pdf with wicked_pdf gem in rails?

Posted: 14 Dec 2016 06:30 AM PST

I am trying to generate a pdf by using wicked_pdf gem in my rails Application. i am having following code in my files.

gemfile     gem 'wicked_pdf'   gem 'wkhtmltopdf-binary'  

and in config/initializers/wicked_pdf.rb file

WickedPdf.config = {    # Path to the wkhtmltopdf executable: This usually isn't needed if using    # one of the wkhtmltopdf-binary family of gems.    # exe_path: '/usr/local/bin/wkhtmltopdf',    #   or    # exe_path: Gem.bin_path('wkhtmltopdf-binary', 'wkhtmltopdf')      # Layout file to be used for all PDFs    # (but can be overridden in `render :pdf` calls)    # layout: 'pdf.html',  }    module WickedPdfHelper    if Rails.env.development?      if RbConfig::CONFIG['host_os'] =~ /linux/        executable = RbConfig::CONFIG['host_cpu'] == 'x86_64' ?  'wkhtmltopdf_linux_x64' : 'wkhtmltopdf_linux_386'      elsif RbConfig::CONFIG['host_os'] =~ /darwin/        executable = 'wkhtmltopdf_darwin_386'      else        raise 'Invalid platform. Must be running linux or intel-based Mac OS.'      end        WickedPdf.config = { exe_path:  "#{Gem.bin_path('wkhtmltopdf-binary').match(/(.+)\/.+/).captures.first}/#{executable}"  }    end  end  

and in controller

  def show      respond_to do |format|        format.html        format.pdf do      render pdf: "file_name"   # Excluding ".pdf" extension.        end      end    end  

in /config/initializers/mime_types.rb

Mime::Type.register "application/xls", :xls  Mime::Type.register "application/xlsx", :xlsx  Mime::Type.register "application/pdf", :pdf unless Mime::Type.lookup_by_extension(:pdf)  

and in the file views/invoises/show.pdf.erb

    <p>        Invoice No:        <%= @invoise.invoice_no %>      </p>      <p>      Due date:      <%= @invoise.due_date %>    </p>      <p>      Total Amount:      <%= @invoise.total_amount %>    </p>  

and the url i am clicking in the browser is /invoises/BRUqWOeEVNSN6GCwxQqLGg%253D%253D.pdf

Iam unable to generate pdf file. And i am not getting any error also. when i click the above url my webpage is keep on loading. i am not getting any output.

Active admin multiple select filter

Posted: 14 Dec 2016 06:26 AM PST

I'm looking to make a filter on my admin page for a user to show users who have both Subject_A and Subject_B.

Using the following line of code I've been able to filter for the users who have either Subject_A or Subject_B or both.

filter :universities, as: :select, multiple: true  

Is there a way to create a filter using Active Admin to filter for users that only have both Subject_A and Subject_B?

Excel file Corrupt/Junk data when it open in Window OS

Posted: 14 Dec 2016 06:21 AM PST

I am using Rails 4. I have created functionality using Spreadsheet gem update existing excel sheet in which some formula's already exist and based on it i calculate some data which come from database.

My issue is that when i open that excel file in windows os. Excel file corrupt or junk my data.

It is open perfectly in Linux and if i send that excel file mannualy in windows os,it also working fine. But when i download from Window os and open it. my file was corrupted.

Thanks in advance.

Making URL look much neater - Rails 5

Posted: 14 Dec 2016 06:34 AM PST

I am unsure how to make my url much neater or prettier. could one kindly advise me

i currently have this url:

http://www.example.com/speed-meetings/dine%20with%20index%20venture%20capital  

and would like it to look like the below url:

http://www.example.com/speed-meetings/dine-with-index-venture-capital  

my route file:

get 'speed-meetings/:title', controller: 'speed_meetings', action: 'show'  

views/events/index.html.erb

<td><%= link_to 'show', "/speed-meetings/#{event.title}" %></td>  

Paginate multiple models with Ajax & Params

Posted: 14 Dec 2016 06:04 AM PST

In my app I allow users to like item/cover object which they can later view in their profile.

I have a profile model that shows a list of items and covers in separate tabs. A user clicks on a link to selects which list to view, which sends the object name to params[:filter] and reloads the page with the correct list.

I am now trying to create infinite scroll for both lists with Kaminari and ajax. It works fine for each list seperatly but when i try to use an if statement with params (in profiles/show.js.haml) the loading breaks. any thoughts?

profiles_controller.rb

class ProfilesController < ApplicationController    def show        @covers = @user.get_voted(Cover).page(params[:page])       @items = @user.get_voted(Item).page(params[:page])      respond_to :html, :js              end  end  

profiles/show.html.haml

.menu    = link_to 'Covers', profile_path(filter: "covers")    = link_to 'Items', profile_path(filter: "items")   .objects    = render 'profiles/covers' if !params[:filter] || params[:filter] == "covers"    = render 'profiles/items' if params[:filter] == "items"  

profiles/_covers.rb

- if @covers.any?      .covers= render @covers      .pagination= link_to_next_page @covers, 'View More', params: params, remote: true  - else      = "No covers yet..."  

profiles/_items.rb

- if @items.any?      .items= render @items      .pagination= link_to_next_page @items, 'View More', params: params, remote: true  - else      = "No items yet..."   

profiles/show.js.haml

- if !params[:filter] || params[:filter] == "covers"      $('.covers').append("#{j render @covers}");      - if @covers.last_page?        $('.pagination').remove();          - else        $('.pagination').html("#{j link_to_next_page(@covers,'View More', params: params, remote: true)}");    - if params[:filter] == "items"      $('.items').append("#{j render @items}");      - if @items.last_page?        $('.pagination').remove();          - else          $('.pagination').html("#{j link_to_next_page(@items,'View More', params: params, remote: true)}");  

app/assets/javascripts/pagination.js

$(function() {    if ($('.pagination').size() > 0) {      $(window).on('scroll', function() {        var next_page_url = $('.pagination a[rel=next]').attr('href');        if (next_page_url && $(window).scrollTop() > $(document).height() - $(window).height() - 200) {          $('.pagination').html('<img src="/assets/ajax-loader.gif" alt="Loading..."/>');          $.getScript(next_page_url);    }  });  

} });

Ruby on Rails: Multiple Foreign Key same table

Posted: 14 Dec 2016 07:27 AM PST

I have two models:

class Word < ApplicationRecord    has_many :g_words, class_name: 'Translation', foreign_key: 'g_id'    has_many :v_words, class_name: 'Translation', foreign_key: 'v_id'  end    class Translation < ApplicationRecord    belongs_to :g, class_name: 'Word', required: true    belongs_to :v, class_name: 'Word', required: true  end  

Table Translations

t.text "note", limit: 65535  t.datetime "created_at", null: false  t.datetime "updated_at", null: false  t.integer  "g_id"  t.integer  "v_id"  

In table Words I already inserted 2 values:

id     body  1      Home  2      Maison  

When I create a new Translation with

g_id     v_id  1        2  

Then the following error appears. enter image description here

I don't know whether I implented the associations wrong or I declared the wrong foreign Keys. I really don't know where to start finding the error. I hope you can help me! Thank you!

Leaflet Marker not found production env

Posted: 14 Dec 2016 06:24 AM PST

I got a problem with leaflet.

Everything is working fine in development, but in production, my app isn't able to locate the marker-icon.png and marker-shadow.png images.

It is looking for the path assets/station/images/marker-icon.png

Leaflet js is including like this in my html.erb file

<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.5/leaflet.js"></script>    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.5/leaflet.css" />  

If someone can help!

Take text_filed value in a variable using controller and views in rails

Posted: 14 Dec 2016 06:40 AM PST

I am new in ruby on rails. I want to take text_field value in a variable and variable define in the controller method.

When will I click on the submit button then the value of test_filed insert into controller method variable.

this is my _step.html.erb

<%= form_for :validation_screens, url: candidate_capture_validation_process_path(@validation_screen), method: :get do |f| %>    <div class="form-group">      <label class="control-label">Role / Designation</label>      <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span>        <%= f.text_field :role, {disabled: true, :value=>job.title, class: 'form-control' } %>      </div>    </div>      <div class="form-group">      <label class="control-label">Candidate Name</label>      <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span>        <%= f.text_field :applied_candidate_name, {disabled: true, :value=>applied_candidate.first_name+" "+applied_candidate.last_name, class: 'form-control' } %>      </div>    </div>      <div class="form-group">      <label class="control-label">Apply Name</label>      <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span>        <%= f.text_field :emp_candidate_name, {disabled: true, :value=>user.first_name+" "+user.last_name, class: 'form-control' } %>      </div>    </div>  <% end %>  

Here I want to take <%= f.text_filed :emp_candidate_name %>

This is my controller candidate_controller.rb

class CandidateController < BaseController        def capture_validation_process          logger.debug "candidate work flow: #{params[:applied_candidate_name].inspect}"            can_name = params[:applied_candidate_name];            @validation_screen = ValidationScreen.new(save_validate_process_params)          @validation_screen.save      end    end  

then I got this output

User Load (0.8ms) SELECT users.* FROM users WHERE users.id = 11 ORDER BY users.id ASC LIMIT 1 candidate work flow: nil

Please tell me where I am wrong, and what is problems

Changing a readonly input text in Active Admin

Posted: 14 Dec 2016 05:42 AM PST

I have an association where a code has an influencer. I want to show the influencer username as readonly in the code form.

Right now I'm doing:

form do |f|  f.inputs 'Code' do    f.input :influencer, input_html: { readonly: true, disabled: true  }, as: :string if !f.object.new_record?  

But I get this and I want the influencer name or username.

I need a field displayed. Not the object.

Ideas?

What's the best way to make AJAX calls in Rails?

Posted: 14 Dec 2016 06:09 AM PST

Include in app/assets/javascripts/*.coffee files ?

Include in *.html.erb file with <script></script> ?

Include in partial and render it in view ?

Something else ?

Thank you !

InvalidForeignKey Apartment Gem when creating records

Posted: 14 Dec 2016 05:22 AM PST

I have excluded user model in apartment initializer file.

config.excluded_models = %w{Franchise User Franchiser}  

I have a ternary model between project and user but when i add members it throughs beneath error.

ActiveRecord::InvalidForeignKey (PG::ForeignKeyViolation: ERROR:  insert or update on table "members" violates foreign key constraint "fk_rails_2e88fb7ce9"  DETAIL:  Key (user_id)=(6) is not present in table "users".  : INSERT INTO "members" ("user_id", "project_id", "created_at", "updated_at", "email") VALUES ($1, $2, $3, $4, $5) RETURNING "id"):  

Any help will be apperciated.

Michael Hartl's Rails tutorial chapter 11 & 12: multiple erros and mails not being send

Posted: 14 Dec 2016 05:17 AM PST

I'm currently at step 12 with the rails tutorial and am having problems with sending the account activation emails and visiting certain pages( i get errors)

When requesting a password reset I get the following error

NameError in PasswordResetsController#create    uninitialized constant User::FILL_IN    Extracted source (around line #62):      def create_reset_digest      self.reset_token = User.new_token        (the code below is highlighted red)        update_columns(reset_digest:  FILL_IN, reset_sent_at: FILL_IN)      end      # Sends password reset email.  

source being:

app/models/user.rb:62:in `create_reset_digest'  app/controllers/password_resets_controller.rb:12:in `create'  

app/models/user.rb

class User < ApplicationRecord      attr_accessor :remember_token, :activation_token, :reset_token    before_save   :downcase_email    before_create :create_activation_digest    validates :name,  presence: true, length: { maximum: 50 }    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 }, allow_nil: true      # 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        # Returns a random token.    def User.new_token      SecureRandom.urlsafe_base64    end      # Remembers a user in the database for use in persistent sessions.    def remember      self.remember_token = User.new_token      update_attribute(:remember_digest, User.digest(remember_token))    end      # Returns true if the given token matches the digest.    def authenticated?(remember_token)      return false if remember_digest.nil?      BCrypt::Password.new(remember_digest).is_password?(remember_token)    end      # Forgets a user.    def forget      update_attribute(:remember_digest, nil)    end      def authenticated?(attribute, token)      digest = send("#{attribute}_digest")      return false if digest.nil?      BCrypt::Password.new(digest).is_password?(token)    end      # Activates an account.    def activate      update_columns(activated: FILL_IN, activated_at: FILL_IN)    end      # Sends activation email.    def send_activation_email      UserMailer.account_activation(self).deliver_now    end      # Sets the password reset attributes.    def create_reset_digest      self.reset_token = User.new_token      update_columns(reset_digest:  FILL_IN, reset_sent_at: FILL_IN)    end      # Sends password reset email.    def send_password_reset_email      UserMailer.password_reset(self).deliver_now    end        # Returns true if a password reset has expired.    def password_reset_expired?      reset_sent_at < 2.hours.ago    end      private        # Converts email to all lower-case.      def downcase_email        self.email = email.downcase      end        # Creates and assigns the activation token and digest.      def create_activation_digest        self.activation_token  = User.new_token        self.activation_digest = User.digest(activation_token)      end  end  

app/controllers/password_resets_controller.rb

class PasswordResetsController < ApplicationController    before_action :get_user,         only: [:edit, :update]    before_action :valid_user,       only: [:edit, :update]    before_action :check_expiration, only: [:edit, :update]    # Case (1)      def new    end      def create      @user = User.find_by(email: params[:password_reset][:email].downcase)      if @user        @user.create_reset_digest        @user.send_password_reset_email        flash[:info] = "Email sent with password reset instructions"        redirect_to root_url      else        flash.now[:danger] = "Email address not found"        render 'new'      end    end      def edit    end      def update      if params[:user][:password].empty?        @user.errors.add(:password, "can't be empty")        render 'edit'      elsif @user.update_attributes(user_params)        log_in @user        @user.update_attribute(:reset_digest, nil)        flash[:success] = "Password has been reset."        redirect_to @user      else        render 'edit'      end    end      private        def user_params        params.require(:user).permit(:password, :password_confirmation)      end        # Before filters        def get_user        @user = User.find_by(email: params[:email])      end        # Confirms a valid user.      def valid_user        unless (@user && @user.activated? &&                @user.authenticated?(:reset, params[:id]))          redirect_to root_url        end      end        # Checks expiration of reset token.      def check_expiration        if @user.password_reset_expired?          flash[:danger] = "Password reset has expired."          redirect_to new_password_reset_url        end      end  end  

When i try to view a user i get the following error

NameError in UsersController#show  uninitialized constant UsersController::FILL_IN    Extracted source (around line #12):      def show      @user = User.find(params[:id])        (the code below being red)        redirect_to root_url and return unless FILL_IN      end      def new  

source being :

app/controllers/users_controller.rb:12:in `show'  

app/controllers/users_controller.rb

class UsersController < ApplicationController    before_action :logged_in_user, only: [:index, :edit, :update, :destroy]    before_action :correct_user,   only: [:edit, :update]    before_action :admin_user,     only: :destroy      def index      @users = User.where(activated: FILL_IN).paginate(page: params[:page])    end      def show      @user = User.find(params[:id])      redirect_to root_url and return unless FILL_IN    end      def new      @user = User.new    end      def create      @user = User.new(user_params)      if @user.save        @user.send_activation_email        flash[:info] = "Please check your email to activate your account."        redirect_to root_url      else        render 'new'      end    end      def edit      @user = User.find(params[:id])    end      def update      @user = User.find(params[:id])      if @user.update_attributes(user_params)              flash[:success] = "Profile updated"        redirect_to @user      else        render 'edit'      end    end       def destroy      User.find(params[:id]).destroy      flash[:success] = "User deleted"      redirect_to users_url    end        # Returns true if the given token matches the digest.    def authenticated?(attribute, token)      digest = send("#{attribute}_digest")      return false if digest.nil?      BCrypt::Password.new(digest).is_password?(token)    end      private        def user_params        params.require(:user).permit(:name, :company, :phone, :email, :password,                                     :password_confirmation)      end    # Confirms a logged-in user.      def logged_in_user        unless logged_in?               store_location          flash[:danger] = "Please log in."          redirect_to login_url        end      end        # Confirms the correct user.      def correct_user        @user = User.find(params[:id])        redirect_to(root_url) unless @user == current_user      end            def admin_user        redirect_to(root_url) unless current_user.admin?      end    end  

I've been at this for over a day searching for answers on different posts and retracing and redoing my steps, but I've got no clue what I've done wrong.

I can't visit the user pages and when I submit forget password i get errors

Recommendify VS Recommedable

Posted: 14 Dec 2016 05:15 AM PST

I'm now trying to make a recommend function to my Rails app, and I found two gems, Recommendify and Recommendable. I just want to introduce Collaborative Filtering Techniques, but I can't get the difference between these two gems. Which is the better choice?

rails create element fail with wrong number of arguments (given 1, expected 0)

Posted: 14 Dec 2016 05:12 AM PST

I rencently take a "old" rails project

I run bundle install and give me arror with json 1.8.0 then fix it with bundle update and bundle install

Then run rake db:schema:load

And when I run rake db:seed give the error:

ArgumentError: wrong number of arguments (given 1, expected 0)

I detele all lines of seeds.rb and put only one create and fail with the same error

Also open a console (rails console) and try two create with different models and fails

irb(main):002:0> Group.create( name: "Test" )     (0.5ms)  BEGIN     (0.2ms)  ROLLBACK  ArgumentError: wrong number of arguments (given 1, expected 0)      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/connection_adapters/postgresql/database_statements.rb:160:in `initialize'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/connection_adapters/postgresql/database_statements.rb:160:in `new'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/connection_adapters/postgresql/database_statements.rb:160:in `substitute_at'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/relation.rb:99:in `block in substitute_values'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/relation.rb:98:in `each'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/relation.rb:98:in `each_with_index'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/relation.rb:98:in `substitute_values'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/relation.rb:58:in `insert'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/persistence.rb:521:in `_create_record'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/counter_cache.rb:139:in `_create_record'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/attribute_methods/dirty.rb:122:in `_create_record'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/callbacks.rb:306:in `block in _create_record'      from /var/lib/gems/2.3.0/gems/activesupport-4.2.0.beta2/lib/active_support/callbacks.rb:83:in `run_callbacks'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/callbacks.rb:306:in `_create_record'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/timestamp.rb:57:in `_create_record'      from /var/lib/gems/2.3.0/gems/activerecord-4.2.0.beta2/lib/active_record/persistence.rb:501:in `create_or_update'  ... 23 levels...      from /var/lib/gems/2.3.0/gems/railties-4.2.0.beta2/lib/rails/commands/console.rb:9:in `start'      from /var/lib/gems/2.3.0/gems/railties-4.2.0.beta2/lib/rails/commands/commands_tasks.rb:68:in `console'      from /var/lib/gems/2.3.0/gems/railties-4.2.0.beta2/lib/rails/commands/commands_tasks.rb:39:in `run_command!'      from /var/lib/gems/2.3.0/gems/railties-4.2.0.beta2/lib/rails/commands.rb:17:in `<top (required)>'      from /var/lib/gems/2.3.0/gems/activesupport-4.2.0.beta2/lib/active_support/dependencies.rb:248:in `require'      from /var/lib/gems/2.3.0/gems/activesupport-4.2.0.beta2/lib/active_support/dependencies.rb:248:in `block in require'      from /var/lib/gems/2.3.0/gems/activesupport-4.2.0.beta2/lib/active_support/dependencies.rb:233:in `load_dependency'      from /var/lib/gems/2.3.0/gems/activesupport-4.2.0.beta2/lib/active_support/dependencies.rb:248:in `require'      from /home/inye/Escritorio/zembia/aiurveda/bin/rails:8:in `<top (required)>'      from /var/lib/gems/2.3.0/gems/activesupport-4.2.0.beta2/lib/active_support/dependencies.rb:242:in `load'      from /var/lib/gems/2.3.0/gems/activesupport-4.2.0.beta2/lib/active_support/dependencies.rb:242:in `block in load'      from /var/lib/gems/2.3.0/gems/activesupport-4.2.0.beta2/lib/active_support/dependencies.rb:233:in `load_dependency'      from /var/lib/gems/2.3.0/gems/activesupport-4.2.0.beta2/lib/active_support/dependencies.rb:242:in `load'      from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from -e:1:in `<main>'  

I can't get a search bar to appear in my Ruby application

Posted: 14 Dec 2016 05:51 AM PST

I have a Ruby application and am trying to implement a search function. I have the code to handle the search request but I can't get the search bar to appear, I have coded it into my application.html.haml but I get an Illegal Nesting error. What am I doing wrong?

%body        %header            .wrapper.clearfix                #logo= link_to "Scribble", root_path                    <li><%= form_tag(search_path, method: :get) do %>                        <%= text_field_tag(:post_title, params[:post_title]) %>                        <%= submit_tag "Search" %>                    <% end %>                %nav                    - if user_signed_in?                        = link_to current_user.name, edit_user_registration_path                        = link_to "Add New Inspiration", new_post_path, class: "button"                    - else                        = link_to "Sign in", new_user_session_path                        = link_to "Sign Up", new_user_registration_path, class: "button"        %p.notice= notice    

Rails - Model with attributes, which are not stored in the database

Posted: 14 Dec 2016 06:56 AM PST

The whole project is build like that: I've got an api which provides data and saves data. Than another Application which converts the data of the data api into "nice and clean" data. and than a frontend, which takes the nice and clean data.

In the Middle part, I got the Model Field. It has multiple Attributes like: id, area, etc. those attributes are also in the schema.rb. Now I also have attributes like: field_nr which are not in the schema.rb. But taken from the api, converted and then printed as json. Now I have to read from the field model the attribute field_nr, which is not in the schema.rb/database. How can I read those attributes?

Thanks for your help & just ask if something is unclear

Rails 5 RESTful API with advanced relations

Posted: 14 Dec 2016 05:23 AM PST

I have many resources with advanced relations (habtm/hm/hmt etc..), everything you can imagine, but now it's time to write a beautiful routing for this API. The problem is, I can't fin the best practices about nested resource + advanced relations ro do my routing, here is what I am trying to do:

Here are my models with the concerned relations

# app/models/candidate.rb  class Candidate < ApplicationRecord    include Sociable, Locatable      belongs_to :user    has_many :sourcing_accounts    has_many :accounts, through: :sourcing_accounts    has_many :users, through: :sourcing_accounts  end    # app/models/sourcing_account.rb  class SourcingAccount < ApplicationRecord    belongs_to :account    belongs_to :candidate    belongs_to :user  end    # app/models/user.rb  class User < ApplicationRecord    include Sociable      has_many :candidates    has_many :campaigns    has_many :sourcing_account  end  

For this example, I am willing to permit to create a relation between a Candidate and a User by creating a SourcingAccount.

resources :candidates do    resources :accounts    resources :users, only: [:index] do      post :remove      post :add    end  end  

It generates:

v1_candidate_user_remove POST   /v1/candidates/:candidate_id/users/:user_id/remove(.:format) api/v1/users#remove {:subdomain=>"api", :format=>:json}     v1_candidate_user_add POST   /v1/candidates/:candidate_id/users/:user_id/add(.:format)    api/v1/users#add {:subdomain=>"api", :format=>:json}  

I did not found anything about this. Is there best practices ??? If not, what do you think would be the best for this case ?

Without precisions, Rails wants to route this to users#remove and users#add, which I think is totally wrong. These actions must not belong to the users controller.

Bonus:

What should look like a polymorphic route to create an Account belonging to 2 other models (with presence validation) the 2 models are Source and the other one is polymorphic [Candidate,User] # for example, (they are Sociable models)

Problems with authorization with SecureCompare

Posted: 14 Dec 2016 03:51 AM PST

I wanted to build API for my existing application. The special authentication token was generated and added to the database. The problem is that when it comes to comparing between token sent by user application with the one defined in the database, I get such error:

NameError (uninitialized constant ActiveSupport::SecurityUtils): app/controllers/api/v1/base_controller.rb:64:in `authenticate_user!'

Rendered /home/snow/.rvm/gems/ruby-2.0.0-p643/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_source.erb (25.4ms)

Rendered /home/snow/.rvm/gems/ruby-2.0.0-p643/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.8ms)

Rendered /home/snow/.rvm/gems/ruby-2.0.0-p643/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (29.9ms)

Rendered /home/snow/.rvm/gems/ruby-2.0.0-p643/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (74.0ms)

Or you can see the response from postman: enter image description here

Searching the Web for answer, it appeared that it may be caused by the incompatibility of Rails version and secure_compare method. (My application is built on Rails 4.0.2 while it is needed to use Rails 4.2.0.) Is rails upgrading the only solution for my problem, or is the any other way to securely compare tokens without using ActiveSupport::SecurityUtils ?

Authentication code is here:

def authenticate_user!      token, options = ActionController::HttpAuthentication::Token.token_and_options(request)      user_phone_number = options.blank?? nil : options[:phone_number]      user = user_phone_number && User.find_by(phone_number: user_phone_number)        if user && ActiveSupport::SecurityUtils.secure_compare(user.authentication_token, token)          @current_user = user      else          return unauthenticated!      end  end  

Rails FactoryGirl - Create specific factories in order to meet fk dependancies

Posted: 14 Dec 2016 04:09 AM PST

Factories are defined in multiple files under /factories/ or in the factories.rb file

spec/factories/*.rb  spec/factories.rb  

The model customer test needs the customer factory. This factory has a foreign key pointing to an address factory.

  • Address factory is defined in /spec/factories.rb
  • Customer factory is defined in spec/factories/customer.rb

Now if i run

rspec spec/model/customer_spec.rb  

i get the following error

postgresql_adapter.rb:602:in `exec_prepared': PG::ForeignKeyViolation:  ERROR:  insert or update on table "customers" violates foreign key constraint "fk_rails_580b7e1bd8" (ActiveRecord::InvalidForeignKey)  DETAIL:  Key (address_id)=(1) is not present in table "addresses".  : INSERT INTO "customers" ("date_of_birth", "created_at", "updated_at", , "female_household_members", "male_household_members", "pin_code", "national_id", ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id"  

FactoryGril tries to build the customer factory first and failes because of the missing entry in the address table.

How can i avoid these dependency issues? Can i somehow define to build some basic factories first ?

Ruby-On-Rails how to display image uploaded by user

Posted: 14 Dec 2016 04:32 AM PST

I am using Carrierwave so that a user can upload an image. I am making a blog website. I have no errors but the image is not appearing. I want the image to appear in the post VIEW. Here is my code:

Post.rb

mount_uploader :image, ImageUploader  

Posts _form.html.erb

  <div>      <%= form_for @post do |f|%>      <%= f.label :image %>      <%= f.file_field :image %>    </div>  

image_uploader.rb

  def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end      def extension_white_list      %w(jpg jpeg gif png)    end  

Posts show.html.erb

<strong>Image:</strong>      <%= image_tag @post.image_url%>  </p>  

When I run my application and view a post it just says Image: with no image underneath it.

UPDATE:

I installed ImageMagick/GraphicsMagick, and when I go to save post it says:

1 error prohibited this post from being saved:  Image Failed to manipulate with MiniMagick, maybe it is not an image? `Original Error: ImageMagick/GraphicsMagick is not installed`  

and underneath it displays the image but it wont save the post.

Elasticsearch complex operators and analyzers

Posted: 14 Dec 2016 03:36 AM PST

I'm trying to create search by Candidates that includes nested models fields and should have breakwords. E.x:

Candidate.search('candidate_requirement.location:(Lentimas AND Town) OR requisitions.requisition_number:45423', size: Candidate.count)  

For now, when I do this search without 'AND' and 'OR', It breaks location: 'Lentimas Town' into 2 words 'Lentimas', 'Town', but I need it to be searched together. How to make that possible to search values divided by comma for example. Like:

search('location:My Location, first_name:First Name')  

Operator between args should be OR.

Here is my trying:

settings index: {    analysis: {      tokenizer: {        comma: {          type: 'pattern',          pattern: ','        }      },      analyzer: {        comma: {          type: :custom,          tokenizer: 'comma',        }      }    }  } do    mapping do      indexes :requisitions do        indexes :requisition_number, taype: 'string', analyzer: 'comma'      end        indexes :candidate_requirement do        indexes :location, type: 'string', analyzer: 'comma'          indexes :industry, type: 'string', analyzer: 'comma'      end    end  end    def as_indexed_json(_options = {})    as_json(      only: [],      include: {        requisitions: { only: [:requisition_number] },        candidate_requirement: { only: [:location, :industry] }      }    )  end  

Rails: After creating a record (e.g. a user) update another table (e.g. not the users table)?

Posted: 14 Dec 2016 04:26 AM PST

In my application I have users and fake posts. What I want: For each user, the fake posts should be displayed in a random order - however the (fake) timestamp associated with the fake-posts should be chronological. To make it clearer:

User A sees:   - Post 1 created at 15.12.2016 - 14:00       - Post 2 created at 15.12.2016 - 13:00      - Post 3 created at 14.12.2016 - 23:00    User B sees:  - Post 3 created at 15.12.2016 - 14:00   - Post 1 created at 15.12.2016 - 13:00  - Post 2 created at 14.12.2016 - 23:00  

I have created a new table with those columns:

fakepost_id | user_id | fake_timestamp  

My models look something like this:

# fakepost.rb  class Fakepost < ApplicationRecord    has_many :randomized  end    # user.rb  class User < ApplicationRecord    has_many :randomized  end    # randomized.rb  class Randomized < ApplicationRecord    belongs_to :user    belongs_to :fakepost  end  

Now I want to do the following (I only have pseudocode by now because I have no idea how to implement it :(...)

  • When a new user is created...
  • get all the fakeposts and...
  • write into the new table for each fakepost: the fakepost_id, the user_id of the newly created user, and a random time in the past.

I know that in my user.rb model I can define an after_create callback, but how do I get all the fakeposts in my user model (they are not associated) and how do I write into another table (not the users table)? Or should I create a randomize.rb model?

No comments:

Post a Comment