Friday, May 20, 2016

Case insensitive search using IN operator in Ruby on Rails and PostgreSQL | Fixed issues

Case insensitive search using IN operator in Ruby on Rails and PostgreSQL | Fixed issues


Case insensitive search using IN operator in Ruby on Rails and PostgreSQL

Posted: 20 May 2016 06:58 AM PDT

I'm new to ROR and trying to implement search in PostgreSQL database using Active Record. I've found that to make search case insensitive I can use ILIKE operator instead of equals and LIKE but not sure what to do when I need to use IN operator.

I'm getting field name and collection of values which I need to check and case sensitive search works like that

records = records.where(filter['fieldName'] => filter['value'])  

where filter['value'] is an array.

Is there a way to update that line to make it case insensitive?

If no then I believe the only way is to loop through that array and split IN into many OR operations and use ILIKE for every single value in that array(however I'm not sure how use OR with Active Record)?

Thanks!

Rails Activerecord, Nested Validations

Posted: 20 May 2016 06:55 AM PDT

I've been worrying this bug for too many days and I'm not sure what I'm missing.

I have a parent model named 'product' and a child of it 'product_attachment' Validation within child model is successful on create to disallow a blank image field via /product_attachments#new

However, when using it through its parent form (files below) when I expect it to fail, Activerecord is ignoring the error, and my controller is complaining that it is blank.

I'm currently in the understanding that using the 'validates_associated' would validate the child model as part of the Parent's process but this has not been working. Instead of passing a happy failed validation mid-form to allow user to take action, we leave form and the controller tries to process the create method which fails due to no attachment. Since I should always have an attachment have been trying to fix this validation to no avail.

Any help appreciated, I've include similar code samples before for your feedback. I'm fairly new to rails so I'm hoping I'm mis-using a key syntax or context.

Also curious what cause is and what best way was to troubleshoot as I'm still developing good debug practices.

product.rb

class Product < ActiveRecord::Base      has_many :product_attachments    validates_presence_of :title, :message =>  "You must provide a name for this product."    accepts_nested_attributes_for :product_attachments, allow_destroy: true#,     validates_associated :product_attachments  end  

product_attachment.rb (carrierwave to handle uploading used here, seems to work fine)

class ProductAttachment < ActiveRecord::Base    belongs_to :product     mount_uploader :image, ImageUploader    validates_presence_of :image, :message =>  "You must upload an image to go with this item."  end  

products_controller.rb

class ProductsController < ApplicationController    before_action :set_product, only: [:show, :edit, :update, :destroy]      def index      @products = Product.all    end      def show      @product_attachments = @product.product_attachments.all    end      def new      @product = Product.new      @product_attachment = @product.product_attachments.build    end      def edit    end      def create      @product = Product.new(product_params)      respond_to do |format|        if @product.save          params[:product_attachments]['image'].each do |a|            @product_attachment = @product.product_attachments.create!(:image => a)          end          format.html { redirect_to @product, notice: 'Product was successfully created.' }        else #- when would this fire?          format.html { render :new }        end      end    end      def update      respond_to do |format|        if @product.update(product_params)            params[:product_attachments]['image'].each do |a|              @product_attachment = @product.product_attachments.create!(:image => a, :post_id => @post.id)            end          format.html { redirect_to @product, notice: 'Product was successfully updated.' }        else #- when would this fire?          format.html { render action: 'new' }        end      end    end      def destroy      @product.destroy      respond_to do |format|        format.html { redirect_to @product, notice: 'Product was successfully destroyed.' }      end    end      private      def set_product        @product = Product.find(params[:id])      end      # we pass the _destroy so the above model has the access to delete      def product_params        params.require(:product).permit(:id, :title, :price, :barcode, :description, product_attachment_attributes: [:id, :product_id, :image, :filename, :image_cache, :_destroy])      end    end  

product_attachments_controller.rb

class ProductAttachmentsController < ApplicationController    before_action :set_product_attachment, only: [:show, :edit, :update, :destroy]      def index      @product_attachments = ProductAttachment.all    end      def show    end      def new      @product_attachment = ProductAttachment.new    end      def edit    end      def create      @product_attachment = ProductAttachment.new(product_attachment_params)        respond_to do |format|        if @product_attachment.save          @product_attachment.image = params[:image]          format.html { redirect_to @product_attachment, notice: 'Product attachment was successfully created.' }        else          format.html { render :new }        end      end    end      def update      respond_to do |format|        if @product_attachment.update(product_attachment_params)          @product_attachment.image = params[:image]          format.html { redirect_to @product_attachment.product, notice: 'Product attachment was successfully updated.' }        else          format.html { render :edit }        end      end    end      def destroy      @product_attachment.destroy      respond_to do |format|        format.html { redirect_to product_attachments_url, notice: 'Product attachment was successfully destroyed.' }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_product_attachment        @product_attachment = ProductAttachment.find(params[:id])      end        def product_attachment_params        params.require(:product_attachment).permit(:id, :product_id, :image, :image_cache)      end  end  

_form.html.slim (using simple_form + slim + cocoon here...)

= simple_form_for @product do |f|      - if @product.errors.any?      #error_explanation        h2          = pluralize(@product.errors.count, "error")          |  prohibited this product from being saved:        ul           - @product.errors.each do |attribute, message|            - if message.is_a?(String)              li= message      = f.input :title    = f.input :price, required: true    = f.input :barcode    = f.input :description      h3 attach product images    #product_attachment      = f.simple_fields_for :product_attachments do |product_attachment|        = render 'product_attachment_fields', f: product_attachment      .links        = link_to_add_association 'add product attachment', f, :product_attachments    = f.submit  

_product_attachment_fields.html.slim Noted I needed to name my file field this way for my controller to use files correctly, but unsure why still.

.nested-fieldsLet me know if I can provide anything else and Thanks again.    = f.file_field :image , :multiple => true , name: "product_attachments[image][]"    = link_to_remove_association "remove", f  

Let me know if I can provide anything else.

Thank you for your time to read/reply.

Edit1: My current method to debug I'm working through as of writing this is to strip out code chunks and test functionality by through browser. I've read I should be more familiar with rails console but have not got there yet.

Error Message: "unsecured or incorrectly secured fault was received from the other party"

Posted: 20 May 2016 06:47 AM PDT

We are communicating with third party, but we are getting this exception,

 an unsecured or incorrectly secured fault was received from the other  party. see the inner faultexception for the fault code and detail.  

we are not able to figure out what could be the issue, we searched and found out that their might be time mismatch issue, but we are only getting fixes for c# , how to fix it in ruby. And how to see the inner fault exception?

RAILS: Don't create new record if exists

Posted: 20 May 2016 06:29 AM PDT

Basically what i need is just method (probably before_create filter) performed when creating new record to check if record with such a title exists (case insensitive) and if it is exists - return finded record and don't create new. If not - create new record.

It is NOT simple exists? check. I have nested form with 9 association. I need method that would be executed before creating record and preform action like i described in topic, so i can reffer that action to each of associated model

Thank you.

Add quality method to refile-imagemagick

Posted: 20 May 2016 06:13 AM PDT

I'm trying to add a quality optimizing method to refile-imagemagick based on this questions/answer: Optimise/compress images uploaded with refile

However how do i do this? I have tried adding this file to lib: lib/refile_optimize.rb

module Refile    class MiniMagick      def quality(percentage)        manipulate! do |img|          unless img.quality == percentage            img.write(current_path) do              self.quality = percentage            end          end            img = yield(img) if block_given?          img        end      end    end  end  

And require it in environment.rb:

# Load the Rails application.  require File.expand_path('../application', __FILE__)    require 'refile_optimize'    # Initialize the Rails application.  Rails.application.initialize!  

I might be completely off with my approach here, so please feel free to suggest a different solution. I wan tot be able to get an image that fills 1920x1080 and is reduced in filesize through the refile helper like so:

<%= attachment_url(@cover, :thumbnail, :fill, 1920, 1080 **missing_something?**) %>  

Convert a Ruby on Rails app from MySQL Database to MsSQL server database?

Posted: 20 May 2016 06:15 AM PDT

I have created ruby on rails application with MySQL database. Now i want to convert my existing rails application database into MsSQL database. Is there any way convert to MsSQL server database?

Thanks.

Rails 3 best_in_place_if how to add "id" attribute to element

Posted: 20 May 2016 05:53 AM PDT

I am using best_in_place_if for inline editing. Here I want to catch the id of current element edited by using the ajax success event of best_in_place.

Below is code snippet I am trying to add id attribute. But when I inspect the html, the value for id attribute is the default value generated by the bes_in_place. As per their doc, its mentioned that the default value can be changed by providing our own value.

The default value for id attribute is shown as id="best_in_place_trip_32_is_active" and I want is only id=32

best_in_place_if(current_user.admin,trip,:is_active, :type => :checkbox, :classes => 'trip_disable', :id => trip.id)  

Please let me know what I am missing.

rails4 scoped has_many association

Posted: 20 May 2016 06:42 AM PDT

In my product_users joint table there is a role column besides the product_id and user_id.

I have this association in my product model.

has_many :owners, -> { where(product_users: { role: "owner" }) },                        through: :product_users, source: :user  

All of the products will have only one "owner" and the rest will be "member". What association should I use to to get the owner of the product instead of an owners collection. So in the views I wanna use product.owner. I couldn't figure out how to use either has_one or belongs_to.

I could use this instance method, but I guess it would be better to define a fine association somehow.

def owner    owners.first  end  

Get the value of Json Array in View from Controller Rails 4

Posted: 20 May 2016 06:18 AM PDT

I need to get the value of the Json Array in the View Page that i have assigned in Rails 4.

My Controller: Profile_controller.rb

class ProfileController < ApplicationController  before_filter :authenticate_user!  def initialize  super  @search_value=[]  end    def search_view  @user_gender=params[:gender]  @user_t_table=User.where.not(gender: @user_gender)  @user_t_table.each do |user|  sql = "SELECT users.id, users.first_name FROM users LEFT JOIN user_profiles ON users.id = user_profiles.user_id LEFT JOIN educations ON users.id = educations.user_id LEFT JOIN usercontacts ON users.id = usercontacts.user_id WHERE  user_profiles.height >='1' AND user_profiles.height <='3' AND user_profiles.marital_status='1' AND user_profiles.mother_tongue='1' AND usercontacts.country_id='1' AND usercontacts.state_id='1' AND usercontacts.city_id='1' AND educations.highest_education='1' AND users.religion_id='1' AND users.caste_id='1' AND users.id ='#{user.id}'"  records_array = ActiveRecord::Base.connection.execute(sql)  @search_value << records_array  end  end  

I need @search_value to be printed in the View page and here is my json Output that i get when i put render to the Value.

Json Output is:

[[{"id":1,"first_name":"sharma","0":1,"1":"sharma"}],[]]

My view Page is search_view.html.erb

<% @search_value.each_with_index do |group,index| %>    <!-- Render stuff -->    <%#<%= group %>    <% group.each_with_index do |child,indexs| %>      <!-- Render child stuff -->      <%= child  %>      <% end %>  <% end %>  

I need to get the id from the json Output. Pls help to get it.

How to perform single sql query to sum columns from grouped results in activerecord?

Posted: 20 May 2016 06:44 AM PDT

I have two models - Parent and Params, where parent has_many params

Currently, my methods looks like:

def total_sum    params.select(      'params.*, (        SUM(mono_volume_annular) +         SUM(day_volume_annular) +         SUM(night_volume_annular) +         SUM(exclusive_volume_annular)      ) AS summed_volume_annular'    ).group('params.id').sum(&:summed_volume_annular)  end  

How can I improve this SQL query to get rid of .sum(&:summed_volume_annular) method call?

Is ActiveRecord changing the encoding on my serialized hash

Posted: 20 May 2016 05:15 AM PDT

I have a Rails application which accepts JSON data from third-party sources, and I believe I am running up against some ActiveRecord behind-the-scenes magic which is recognizing ASCII-8BIT characters in hashes extracted from the JSON and saving them as such to my database no matter what I do.

Here is a simplified description the class ...

class MyClass < ActiveRecord::Base   serialize :data  end  

and of how an object is created ...

a = MyClass.new   a.data = {    "a" =>      {        "b" => "bb",          "c" => "GIF89a\x01\x00\x01\x00\x00\x00\x00\x00!\vNETSCAPE2.0\x03\x01\x00\x00!\x04\t\x00\x00\x01\x00,\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02L\x01\x00;"      }  }  

I believe those are ASCII-8BIT characters, so fair enough if they are saved as such (despite my attempts to UTF8 everything everywhere). But I need these characters to be UTF-8, because when I go to view them I get:

ActionView::Template::Error ("\xEF" from ASCII-8BIT to UTF-8):      64:       <div>      65:         <pre><%= mc.prettify %></pre>      66:       </div>  app/models/my_class.rb:28:in `prettify'  

where line #28 in prettify is:

JSON.pretty_generate(self.data)  

So I sought to re-encode any string in the Hash. I built out functionality to do this (with anonymous classes and refinements to Hash, Array and String), but no matter what, ASCII-8BIT is returned to me. In the simplest terms here is what is happening:

mc = MyClass.find(123)  mc.data['a']['c'].encode!(Encoding.find('UTF-8'), {invalid: :replace, undef: :replace, replace: ''})  mc.data['a']['c'].encoding #=> #<Encoding:UTF-8>  mc.data['a']['c'].valid_encoding? #=> true  mc.save!  mc.reload  mc.data['a']['c'].encoding #=> #<Encoding:ASCII-8BIT> <-- !!!!!  

What is ActiveRecord doing to this hash when it saves it? And what can I do to store a hash permanently with all strings encoded to UTF-8 in a serialized MySQL (v5.6, via the mysql2 gem) mediumtext column (using Ruby 2.2.4 and Rails 4.1.4)?

Make a current Image Uploader to upload multiple images

Posted: 20 May 2016 06:23 AM PDT

I want to make a change on my current model to be able to upload more than one picture. Currently, only one allowed. I have searched stackoverflow but it only shows how I can install carrierwave and make a model to upload multiple picutres FROM SCRATCH. Here, I want to change my current model, so differently.

I will show you what my model look like now.

properties.html.erb

<span class="thumb"><a href="#"><img src="<%=p.image.thumb.url %>"></a></span>  

property.rb

class Property < ActiveRecord::Base      belongs_to :admin      mount_uploader :image, ImageUploader    end  

db -> add_image_to_property.rb

class AddImageToProperty < ActiveRecord::Migration    def change      add_column :properties, :image, :string    end    end  

Hope I could find a detailed explanation.

rubyinstaller devkit install error rake aborted

Posted: 20 May 2016 06:33 AM PDT

I am trying to install rubyinstaller. after

git clone https://github.com/oneclick/rubyinstaller.git  

and get in directory rubinstaller and put command

rake devkit sfx=1  

I get message

/home/leon/rubyinstaller/sandbox/extract_utils/7za.exe" e -y   "downloads/7z920.msi" -o"sandbox/extract_utils" "_7z.sfx" > NUL 2>&1  rake aborted!  Command failed with status (126): ["/home/leon/rubyinstaller/sandbox/extract_...]  /home/leon/rubyinstaller/rake/extracttask.rb:72:in `seven_zip_get'  /home/leon/rubyinstaller/recipes/extract_utils/extract_utils.rake:45:in `block (2 levels) in <top (required)>'  /home/leon/.rvm/gems/ruby-2.2.5/bin/ruby_executable_hooks:15:in `eval'  /home/leon/.rvm/gems/ruby-2.2.5/bin/ruby_executable_hooks:15:in `<main>'  Tasks: TOP => devkit => devkit:build => devkit:msys => devkit:msys:extract => extract_utils => extract_utils:extract_utils  (See full trace by running task with --trace)  

any idea ? i am using UBUNTU 17.3

Counting number of scaffolds Ruby on rails

Posted: 20 May 2016 06:13 AM PDT

I'm made a page scaffold and want users to create only one , so is there any way to count the scaffolds for a specific user and stop him from making more than one .

https://github.com/Hisaan-Anjum/friends

how to save a datetime column in specific time zone in rails?

Posted: 20 May 2016 05:01 AM PDT

currently, I am in indian time_zone. while saving any request which contains any date time column then rails properly deducting the indian offset automatically and saving in the database. And while showing the data I am using the in_time_zone method with indian time_zone. Now in some request there is a datetime column start_date for only this request. I don't want to save in the indian time_zone. Instead I want to menntion a separate time_zone while saving. And while showing the data I want to use in_time_zone method with whichever the time_zone it is saved. But I dont know how to mention the specific timezome while saving. can someboby help me with this.

I18n together with clockwork

Posted: 20 May 2016 04:42 AM PDT

When a model method "model_method" is called from clockwork, I18n.locale always equals to my default locale.

How do I pass the current locale to the model method?

Part of clockwork.rb:

every(10.minutes, 'test') do    Book.delay(:queue => 'some_queue').model_method  end  

Part of book.rb:

def self.model_method    ...    message = I18n.t('some_text')    # always equals to ":en"  end  

Getting value of object id from new method to create

Posted: 20 May 2016 05:18 AM PDT

I have problem with getting value of found id from new method to create.

New method:

  def new      @vacation = Vacation.new      @vacation.person = @person    end  

Result of @person:

#<id: 1, first_name: ... >  

@vacation.person is also good. For now all is well. But after this, when I fill form and click submit:

def create      @vacation = Vacation.new(vacation_params)  end  

Result:

#<Vacation id: ..., person_id: nil >  

But now @person is nil and also @vacation.person is nil. I don't have idea how to send value of id to create method.

Method to find id.

before_action :set_person  private   def set_person     @person = Person.find(params[:id]) unless params[:id].blank?   end  

vacation_params:

def vacation_params      params.require(:vacation).permit(:start_at, :end_at, :free, :reason, :person_id, :accepted)  end  

Want to save all filters that apply on active admin gem model

Posted: 20 May 2016 04:29 AM PDT

I want to save all filters value that apply on a gem , is there any default way in active gem. Otherwise i am getting these filters in params "q" i have to parse it and save into Database. But is there any build in feature in active admin which will let me do the above mention task.

will_paginate for search result?

Posted: 20 May 2016 04:41 AM PDT

I am using will_paginate gem for the pagination on my application. I have created a search action with the following code.

Controller

def index       @transactions = Transaction.all.paginate(:page => params[:page], :per_page => 10)  end    def search      @transactions = Transaction.paginate(:page => params[:page], :per_page => 10).where(:created_at => params[:from_date].to_datetime..(params[:to_date].to_datetime + 1.day))  end  

search.js.erb

$("#searchResult").replaceWith('<div id = "searchResult"><%=j render 'result' %></div>');  

_result.thml.erb

<div>  <%= @transactions.each do |f| %>  ......  ......  <% end %>  </div>  <%= will_paginate @transactions %>  

index.html.erb

<div id = "searchResult">  <%= render = "result"%>  <% end %>  

pagination.js

$(function() {    $(".pagination a").on('click', function(){      $(".pagination").html("Page is loading...");      $.getScript(this.href);      return false;    });  });  

It somehow works for a index action, ajax method works for the links but when the I click on the last or the first page links generates like localhost:3000/control?_=1463743428904&page=1 also, when ever I hit the search, the pagination links throws link like localhost:3000/control/search?from_date=2016-05-18&page=2&to_date=2016-05-20&utf8=%E2%9C%93 which should be like localhost:3000/control?page=1. Is there any solution for this.

How to Join more than 2 tables in Ruby on Rails?

Posted: 20 May 2016 05:07 AM PDT

I have 4 tables users, user_details, categories and galleries I want to show all record in one query. See below my table structure

categories

id  name  

users

id  username  email  password  user_type  is_active (0 or 1)  created_at  modified_at  

user_details

id  user_id  category_id  name  gender  address  phone  

galleries

id  user_id  name  image  is_active  

I want to get all the user information which user id=1 with user_details and category and show her/her all the is_active=1 images from the galleries table

Here is my code -

@user_details = User.eager_load(:Category,:Gallery,:UserDetail).where('users.id'=>20, 'users.is_active'=>1, 'users.user_type'=>2, 'galleries.is_active'=>1).first()  

Here I am getting error message:

Association named 'Category' was not found on User; perhaps you misspelled it?  

Actually I have associate Category in the UserDetails model. So I am unable to get the Category data. Please see my all models -

category.rb

class Category < ActiveRecord::Base    has_many :UserDetail  end  

user.rb

class User < ActiveRecord::Base    #before_save :encrypt_password    has_one :UserDetail, dependent: :destroy    has_many :Gallery, dependent: :destroy  end  

user_detail.rb

class UserDetail < ActiveRecord::Base    belongs_to :User    belongs_to :Category  end  

gallery.rb

class Gallery < ActiveRecord::Base    belongs_to :User  end  

Let me know why categories table not joining. Please Help me for this query.

undefined method `first' for nil:NilClass Rails

Posted: 20 May 2016 04:27 AM PDT

I know this error, i know what it means but in this case it makes absolutely no sense. I have a form that used to work well. And i have another form almost the same working nicely. However this form now gives me this error when i submit the data:

 Showing C:/Sites/mewwd/app/views/wine_lists/_form.html.erb where    ine #189 raised:   undefined method `first' for nil:NilClass Rails  

_form.html.erb

<%= f.collection_select :wine_list_region_id, @regioes, :id, :regiao , {hide_label: true, :selected => @regioes.first.id} , {:style => "width: 120px",:required => true} %>  

Controller

def new  @wine_list = WineList.new  @tipos = WineListType.where(:user_id => [current_user.id, "0"])  @produtores = WineListProducer.where(:user_id => [current_user.id, "0"])  @regioes = WineListRegion.where(:user_id => [current_user.id, "0"])  @dosagens = WineListPriceType.where(:user_id => [current_user.id, "0"])  end  

This collection_select if fetching the data correctly! Everything show's up the way it should but when i submit i get that error and i dont understand why.

rails migration unique key on 3 columns in rails (sql server)

Posted: 20 May 2016 04:10 AM PDT

I have this table on my Database:

create_table :month_holidays_translations, :id => false do |t|    t.integer :month_holidays_id, null: false    t.string :month, null: false    t.string :language, null: false  end  

I want to create a migration that creates a multiple unique key on columns: month_holidays_id, month and language. How I do that? When I do add_index (code below) this create a index but not a unique key in my sql server database.

add_index "month_holidays_translations", ["month_holidays_id", "month", "language"], :unique => true  

Authenticating comments on Rails blog? [on hold]

Posted: 20 May 2016 03:28 AM PDT

I am building a basic Rails blog using devise for admin login. When you view a blog post there is an option for leaving comments at the bottom, but right now anyone can leave a comment.

What I want to do is make it so that when you click on the text_area, a user will be prompted to sign in using a link to their facebook with omniauth or their email address.

How will I go about achieving this?

Thanks in advance.

Rails - Split integer form field into 3 separate sections

Posted: 20 May 2016 03:32 AM PDT

I have a time field which stores an integer(minutes). I want the user to be able to enter in days, hours and minutes in the form rather than entering minutes.

.form-group      = f.label :time, class: "col-sm-2 control-label"      .col-sm-10        = f.text_field :time, class: "form-control"  

Is there an easy way to do this via the form so that I would have...?

.form-group      = f.label :days, class: "col-sm-2 control-label"      .col-sm-10        = f.text_field :days, class: "form-control"  .form-group      = f.label :hours, class: "col-sm-2 control-label"      .col-sm-10        = f.text_field :hours, class: "form-control"  .form-group      = f.label :minutes, class: "col-sm-2 control-label"      .col-sm-10        = f.text_field :minutes, class: "form-control"  

I realise I could just have days,hours and minutes as database fields but I'd rather just keep my single time field.

FactoryGirl.create always fail in spec controller

Posted: 20 May 2016 03:33 AM PDT

So I have users model

I create it with scaffolding

the test is passed in model spec but it always fail in controller spec

my users_controller_spec

require 'rails_helper'    RSpec.describe Api::V1::UsersController, type: :controller do    describe "GET #show" do      before(:each) do        @user = FactoryGirl.create :user        get :show, id: @user.id      end    it { should respond_with 200 }    end  end  

my User's FactoryGirl

FactoryGirl.define do    factory :user do      name "MyString"      sex_id 1     end  end  

I can create user from my console and from my user model spec

FactoryGirl.create :user  

but it always fail when I try to create it from my controller spec

  1) Api::V1::UsersController GET #show    Failure/Error: @user = FactoryGirl.create :user     ActiveRecord::InvalidForeignKey:     PG::ForeignKeyViolation: ERROR:  insert or update on table "users" violates foreign key constraint "fk_rails_12f007df76"     DETAIL:  Key (sex_id)=(1) is not present in table "sexs".     : INSERT INTO "users"    # ------------------   # --- Caused by: ---   # PG::ForeignKeyViolation:   #   ERROR:  insert or update on table "users" violates foreign key constraint "fk_rails_12f007df76"   #   DETAIL:  Key (sex_id)=(1) is not present in table "sexs".   #   /home/user/.rvm/gems/ruby-2.1.8/gems/factory_girl-4.7.0/lib/factory_girl/configuration.rb:18:in `block in initialize'  

How to hide database records from view?

Posted: 20 May 2016 04:12 AM PDT

I'm beginner in Ruby On Rails and I'm reading "Getting Started with Rails" now.

I created models and controllers for Article and Comments, everything ok, I'm able to add comments and they appear on Article view, but besides I see records from database in this format:

  [# Comment id: 1, commenter ... updated_at: "2016-05-20 09:26:25"]  

Why they appear and how to hide it? Code of Article's view show.html.erb:

<p>    <strong>Title:</strong>    <%= @article.title %>  </p>    <p>    <strong>Text:</strong>    <%= @article.text %>  </p>    <h2>Comments</h2>  <%= @article.comments.each do |comment| %>    <p>      <strong>Commenter:</strong>>      <%= comment.commenter %>    </p>    <p>      <strong>Comment:</strong>>      <%= comment.body %>    </p>  <% end %>    <h3>Add a comment</h3>  <%= form_for([@article, @article.comments.build]) do |f| %>    <p>      <%= f.label :commenter %>      <%= f.text_field :commenter %>    </p>    <p>      <%= f.label :body %>      <%= f.text_area :body %>    </p>    <p>      <%= f.submit %>    </p>  <% end %>    <%= link_to 'Edit', edit_article_path(@article) %>  <%= link_to 'Back', articles_path %>  

What is unobtrusive JavaScript in Ruby on Rails

Posted: 20 May 2016 03:00 AM PDT

I am new to Ruby on Rails; I want to know what is unobtrusive JavaScript in Rails.

I Google it and see examples but I can't understand the purpose and meaning of unobtrusive JavaScript.

Is it different from normal JavaScript?

Trying to convert html to image using imgkit and wkhtmltoimage

Posted: 20 May 2016 05:30 AM PDT

Trying to convert the HTML content into image using ImgKit and wkhtmltoimage. Image is converted successfully but facing the issues with fonts (Font Awesome).

The image is not look as it as HTML content.

Attaching 2 images one which have HTML content (HTML-CONTENT.png) and other one is converted to image (HTML-Converted-To-IMAGE.png). You can see the difference in fonts between the 2 images.

enter image description here

enter image description here

Could you please anyone suggest me on this, how can I achieve exact html conversion into image.

Thanks for the help in advance.

Disable HTML respond format in whole Rails App

Posted: 20 May 2016 03:50 AM PDT

I use pure javascript frontend template to handle all requests with Rails via JSON API

However,

I don't know why sometimes the exception will give me the error message in HTML format.

Because I've already set the API request format in JSON

Controller (I only keep format.json in the controller)

format.json { render json: @city.errors, status: :unprocessable_entity }  

Route.rb

  namespace :api do      namespace :v1, defaults: {format: 'json'} do      resources country do          resources city do              .....          end      end      end    end  

How to change ping interval in action cable rails

Posted: 20 May 2016 03:16 AM PDT

I'm using action cable and receiving pings from server after each 3 seconds interval (mentioned in the action cable library). My question is: How to change the ping interval at the time of subscription.

Any idea?

Thanks in Advance.

No comments:

Post a Comment