Thursday, September 15, 2016

How group_by on Rails | Fixed issues

How group_by on Rails | Fixed issues


How group_by on Rails

Posted: 15 Sep 2016 08:55 AM PDT

I am pretty new to ROR and i'm in trouble to achieve this.

I have a Working_hour Model and a Merchant Model, where merchant has_many working_hours and working_hour belongs to Merchant, as follow:

class Merchant < ApplicationRecord     has_many   :working_hours, inverse_of: :merchant, dependent: :destroy    accepts_nested_attributes_for :working_hours, reject_if: :all_blank, allow_destroy: true  end  

Working hour table

create_table "working_hours", force: :cascade do |t|    t.integer  "day"    t.time     "open_time"    t.time     "close_time"    t.integer  "merchant_id"    t.datetime "created_at",  null: false    t.datetime "updated_at",  null: false    t.index ["merchant_id"], name: "index_working_hours_on_merchant_id"  end  

The merchant can have two working_hours for the same day. When I display at the view ordered by day the data retrieved are:

Mon: 10am-13am  Mon: 17pm-20pm  Tue: 10am-13am  Tue: 17pm-21pm  Wed: 10am-13am  

How can I group the working_hours by days and display this way:

Mon: 10am-13am / 17pm-20pm  Tue: 10am-13am / 17pm-21pm  Wed: 10am-13am  

I watched the group_by tutorial from the Railscast, but I don't have a controller to working_hour Model. Any ideas?

Running multiple rake tasks in rails

Posted: 15 Sep 2016 08:47 AM PDT

So i have this

Rake::Task["rake:task1"].invoke  Rake::Task["rake:task2"].invoke  Rake::Task["rake:task3"].invoke  Rake::Task["rake:task4"].invoke  

I'm wondering if its possible to run these all at the same time?

Sam

Fixtures in mail preview

Posted: 15 Sep 2016 08:36 AM PDT

Having the following mailer previewer code:

class RegistrationMailerPreview < ActionMailer::Preview      # Preview this email at http://localhost:3000/rails/mailers/registration_mailer/welcome    def welcome      RegistrationMailer.welcome users(:one)    end    end  

(full file).

Which is unable to reach my fixtures (users(:one)), return a 500 error status and print out the following error:

NoMethodError: undefined method `users' for #RegistrationMailerPreview  

Can we get fixtures entries from mailer previewer?

If yes, I would like to know how to do that.
I have seen that should be possible here, but I can't require test_helper in this file (I don't know why) and I don't understand the difference between ActionMailer::TestCase and ActionMailer::Preview.

If no, is there a way to preview the mail without sending as a parameter User.first, since I could do my tests on a machine on which there is no data filled in the database.

Why is rails app rendering without CSS after creating Cloudfront distribution?

Posted: 15 Sep 2016 08:55 AM PDT

My rails app isn't loading the css or js files now upon trying to implement page cache via cloudfront.

I'm using heroku and I setup cloudfront based on these instructions:

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

Done: "To create a CloudFront distribution you will need an Amazon AWS account. Once logged in you can go to the CloudFront control panel and select 'Create distribution'. When prompted for the delivery method, select 'Web'."

I then added to rails production.rb: config.action_controller.asset_host = "d373p52igaakhgm9.cloudfront.net"

What could have gone wrong with www.anthonygalli.com? I think I followed all the steps.

How to have a form in Rails that supports has_many associations, not yet existing

Posted: 15 Sep 2016 08:24 AM PDT

Suppose each Photo may have many Persons associated with it. Now I might want to add completely new people just in the same form where I'm uploading the photo. Here's what it looks like:

= form_for Photo.new do |f|    - 10.times do      - person = Person.new      = f.fields_for "people[]", person do |prsn|        = prsn.text_field :name  

Problem is, this generates the following HTML for each Person's :name field:

<input type="text" name="photo[person][name]" ...>  

Where I would expect it to generate this:

<input type="text" name="photo[person][][name]" ...>  

What am I doing wrong here?

Active record, results illustration

Posted: 15 Sep 2016 08:34 AM PDT

Can someone explain this?

Post.where(:p_date => ((Time.now - 7.days)..(Time.now))).count  -> 4507  Post.where(:p_date => ((Time.now - 7.days).beginning_of_day..(Time.now).end_of_day)).count  -> 4794  

While p_date is only date type without time.

Thank you

Refactoring front end code by minimizing dependancies

Posted: 15 Sep 2016 08:10 AM PDT

Large web applications tend to accrue a huge array of libraries that support both front-end and back-end functionality. I want to reduce the number of dependencies in order to increase stability and ease of maintenance. I'm looking for a good path to reducing dependencies in a web app that includes libraries such as:

I'm looking for techniques, languages, or frameworks that combine as many of those dependencies as possible.

Here's what I've explored so far:

Refactoring small dependencies and removing unused parts could go a long way.

React would impose discipline on the jQuery spaghetti code and reduce the need for a few of the dependencies.

Elm would go farther towards imposing discipline with its type safety.

ClojureScript would also impose discipline through a functional programming paradigm.

Except for refactoring, all of these potential solutions would introduce some additional complexity of their own in order to integrate with the Ruby on Rails back-end. React seems to have the most replacements for the current dependencies.

The safest path forward seems to be to start with refactoring and gradually introduce one of the functional languages or libraries. How would I refactor with this goal in mind? Would first refactoring to plain JS (i.e. removing jQuery) be useful?

CanCanCan not stopping posts being edited

Posted: 15 Sep 2016 08:31 AM PDT

I'm making a rails project, and I'm trying to implement CanCanCan. I installed the gem and the ran the commands. I then added this to ability.rb:

class Ability    include CanCan::Ability      def initialize(user)      # Define abilities for the passed in user here. For example:          user ||= User.new # guest user (not logged in)        if user.admin?          can :manage, :all        else          can :update, Post do |post|            post.user == user          end          can :destroy, Post do |post|            post.user == user          end          can :create, Post          can :read, :all        end      end  end  

However, now in my project, if I sign into a different user, I can still edit other users posts.

Any help with what I'm missing will be greatly appreciated.

Carrierwave returns path of tmp file instead of actual in a callback

Posted: 15 Sep 2016 07:57 AM PDT

In an application I wanted to send public file URL to a service in an after_create callback. So, the code (simplified) looked like this:

class UserProfile < ApplicationRecord    mount_uploader :video, VideoUploader    after_create :send_url_to_service      private      # Just logs the URL    def send_url_to_service      Rails.logger.info video.url    end  end  

To my frustration, after the upload, the send_url_to_service callback always logged the cached file path - something like 'uploads/tmp/1473900000-123-0001-0123/file.mp4' instead of 'uploads/user_profiles/video/1/file.mp4'. I tried to write a method to form the URL from the actual file path, but it did not work because the file wasn't there yet.

So, the question is, how do you obtain a final file URL in a situation like this?

P. S. Please note, this is a self-answered question, I just wanted to share my experience.

How do I get a dummy database to test my Rails 3.2 engine using minitest?

Posted: 15 Sep 2016 07:56 AM PDT

I'm working on an existing Rails 3.2 site and have been tasked with adding tests to one of the engines using Minitest. My underlying issue here is that there are no rake tasks available beyond rake test. Running anything in this engine's directory will result in the error:

rake aborted!

Don't know how to build task '[insert task here]'

Therefore, I have no access to db:create, db:test:prepare, etc. I've manually created the test database and one of the tables. However, for all my tests, I now receive the following error: SQLite3::SQLException: no such table ... even though the table is in the database and there are fixtures available. How do I get a working dummy database?

iterating with ruby using an if else statement ...(along w. ancestry gem)

Posted: 15 Sep 2016 08:04 AM PDT

Recently started with Rails and am presently using ancestry gem for the first time ...

I am attempting to iterate thru a class of Category objects, that which are stored in a tree structure via the ancestry gem, in order to display buttons,wired to 'link_to' to other category objects, a given category is related to.

The first 3 categories in the database are the roots, and so I will eventually not have enough space in the view to display buttons for all descendants … So, if the category.id is equal to 1, 2 or 3, I would like to display only the children of given category …

However, for all other category objects (with category.ids of 4 and beyond …), I would like to display all the descendants of a given category.

Does anyone have any suggestions on accomplishing, by iterating thru such objects, maybe by using an if else statement using ruby?

Any and all recommendations would be greatly appreciated.

thank you.

tiny tds returning a dead connection object?

Posted: 15 Sep 2016 07:39 AM PDT

I am using tinytds gem to connect to remote microsoft sequel server database from my Ruby on Rails Application. i am getting a connection object which is not active though all the credentials are proper(i mean correct credentials). And its not giving the connection object immeadiately. Its taking seconds to connect and returning a connection object, which is not active. previously i used to get the connection object immeadiately and i used to get a active working connection object. And i Have observed that whenever it takes time to connect to a remote server then at that time i am getting an in active(dead) connection object. And whenever it takes less time to connect to a remote server at that time iam getting a Active connection object which is working fine for me from very long time. suddenly its started taking time to connect and giving a connection object which is not live(dead). i am not getting whats happening.

irb(main):199:0> client = TinyTds::Client.new username: bio_metric_db_info.user_name, password: bio_metric_db_info.password, dataserver: bio_metric_db_info.db_ip_addr ,database: bio_metric_db_info.db_name  => #<TinyTds::Client:0x007f59f63072b0 @query_options={:as=>:hash, :symbolize_keys=>false, :cache_rows=>true, :timezone=>:local, :empty_sets=>true}>  irb(main):200:0> client.active?  => false  irb(main):201:0> client.dead?  => true  irb(main):202:0>   

How to protect visible email address from spam with gem for Ruby 4?

Posted: 15 Sep 2016 07:54 AM PDT

I'd like to obfuscate an email address on my webpage. I'm hoping to avoid JS in case my users deactivate it.

I found this gem: actionview-encoded_mail_to but it doesn't seem to work for me. It shows the full email address on the page (which is good), but it also shows it in the console.

I tried the 3 examples with the same result. The gem appears in my Gemfile so should be correctly installed.

Rails trying to get external database info with ActiveRecord::Base.connection_config

Posted: 15 Sep 2016 07:32 AM PDT

I have a connection to an external database (In addition to the rails database).

I want to be able to show the connection information except for the password in a view.

ActiveRecord::Base.connection_config works fine and shows the connection information for the rails db connection.

However, my external table is

customer_tables:    adapter: sqlserver1    host: sqltest1    port: 1440    database: CUSTOMER    username: xxx    password: xxx    schema_search_path: dbo  

How do I get the info for that connection/db to show as it does for the default rails db?

Rails Polymorphic associations with name space

Posted: 15 Sep 2016 07:25 AM PDT

I want to save different results(default and manual), each result can have a reason. Thought that this would be a good place for a polymorphic association. The Models are namespaced however and this is prooving to be tricker than anticipated. following the guide

app/models/event/reason.rb

#  id              :integer          not null, primary key  #  reasons         :string  #  reasonable_id   :integer  #  reasonable_type :string  #  created_at      :datetime         not null  #  updated_at      :datetime         not null  #    class Event::Reason < ActiveRecord::Base    belongs_to :reasonable, polymorphic: true  end  

app/models/event/result.rb

class Event::Result < ActiveRecord::Base    belongs_to :event    has_one :event_reason, as: :reasonable  end  

app/models/event/manual_result.rb

class Event::ManualResult < ActiveRecord::Base    belongs_to :event    has_one :event_reason, as: :reasonable  end  

But if I try do something like:

Event::ManualResult.last.event_reason    Event::ManualResult Load (5.1ms)  SELECT  "event_manual_results".* FROM "event_manual_results"  ORDER BY "event_manual_results"."id" DESC LIMIT 1    NameError: uninitialized constant Event::ManualResult::EventReason  

or

 Event::Result.last.event_reason     Event::Result Load (0.4ms)  SELECT  "event_results".* FROM "event_results"  ORDER BY "event_results"."id" DESC LIMIT 1     NameError: uninitialized constant Event::Result::EventReason  

It would seem it is expecting the associations to be nested within an additonal layer Event::ManualResult::EventReason and Event::Result::EventReason

Searching an external API through a rails form and displaying the results in the view

Posted: 15 Sep 2016 08:54 AM PDT

I need to search data (tutorials) from an external API with 2 params (tag and device) provided by a form in my rails app.

In my routes I have:

resources :search_lists, only: [:index] do    collection do      post :search    end  end  

Here's what I think I should put in my SearchListsController:

def index    @search_parameter = params[:tags]  end    def search  end  

I'm not sure how I would organize my code and where I should pass the API calls.

Here's my view, rails doesn't recognize the search_lists_url:

<form action="<%= search_lists_url %>">    <input type="text" name="" value="" placeholder="Search by tag">    <label >Filters:</label>    <input type="checkbox" value="first_checkbox">Smarthpone    <input type="checkbox" value="second_checkbox">Tablet    <input type="checkbox" value="third_checkbox">Mac    <br>    <input type="submit" value="Search">  </form>  

Can anyone help me please ? :)

Rails 5 Nested attributes "Unpermitted parameter" - Whitelisted

Posted: 15 Sep 2016 08:50 AM PDT

Error: Unpermitted parameter: properties

I'm whitelisting the properties{} in the request_controller.rb This usually works but not this time.

I'm not been able to save some of the data entered in a form. The 3 fields that are not saving are coming from a dynamic form "request_type". I followed Rails Cast episode 403 for this solution, which I have working well in another project but not in this one.

Source: http://railscasts.com/episodes/403-dynamic-forms

Sorry if this is a duplicate question, but I've looked at several other questions and I can't pin-point what I'm doing wrong here

I've researched several questions here, but I'm still not able to get it to work:
Rails 4 Nested Attributes Unpermitted Parameters
Nested attributes - Unpermitted parameters Rails 4

I'm omitting some stuff to make it easier to read the code. Please ask me if you need to see more.

Here's the log:

Processing by RequestsController#create as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"8EASewOIxY58b+SU+dxd2YAfpjt38IdwNSju69RPwl/OKfx3AfmvLav79igj8CqPbDwi0eJAwojRbtm+C9F6wg==", "request"=>{"name"=>"asdasddaa", "due_date(1i)"=>"2016", "due_date(2i)"=>"9", "due_date(3i)"=>"15", "user_id"=>"1", "project_id"=>"1", "request_type_id"=>"2", "properties"=>{"Name and last name"=>"asdasd", "Mobile"=>"asdada", "Office tel."=>"asdadas"}}, "commit"=>"Create Request"}  Unpermitted parameter: properties  

Update

If I change the request_params to this:

def request_params    params.require(:request).permit(:name, :due_date, :group_id, :user_id, :project_id, :request_type_id, properties:{} ).tap do |whitelisted|      whitelisted[:properties] = params[:request][:properties]    end  end  

See: properties:{}

I get this Error:

Unpermitted parameters: Name and last name, Mobile, Office tel.  

request_controller.rb

  def new      @request = Request.new      @request_type = RequestType.find(params[:request_type_id])      @project = @request_type.project.id    end      def create      @request = Request.new(request_params)        respond_to do |format|        if @request.save          format.html { redirect_to @request, notice: 'Request was successfully created.' }          format.json { render :show, status: :created, location: @request }        else          format.html { render :new }          format.json { render json: @request.errors, status: :unprocessable_entity }        end      end    end        def request_params        params.require(:request).permit(:name, :due_date, :group_id, :user_id, :project_id, :request_type_id, :properties).tap do |whitelisted|          whitelisted[:properties] = params[:request][:properties]          end      end  

models/request.rb

class Request < ApplicationRecord    belongs_to :group    belongs_to :user    belongs_to :project    belongs_to :request_type    serialize :properties, Hash  end  

models/request_type.rb

class RequestType < ApplicationRecord    belongs_to :project    has_many :fields, class_name: "RequestField"    accepts_nested_attributes_for :fields, allow_destroy: true    has_many :requests    end  

models/request_field.rb

class RequestField < ApplicationRecord    belongs_to :request_type  end  

views/requests/new.html.erb

<%= form_for @request do |f| %>      <%= f.fields_for :properties, OpenStruct.new(@request.properties) do |builder| %>      <% @request_type.fields.each do |field| %>        <%= render "requests/fields/#{field.field_type}", field: field, f: builder %>      <% end %>    <% end %>                    <div class="actions">      <%= f.submit class:"btn btn-primary" %>    </div>  <% end %>  

HMT association 3 levels deep

Posted: 15 Sep 2016 07:02 AM PDT

My main objective is for an Album to be able to grab all of the Tracks belonging to a Release. It should be noted that the tracks belong to a DiscSide which belongs to a Disc. Is there a clean way to accomplish this without declaring HMT associations in multiple models?

class Album < ApplicationRecord    has_many :releases, dependent: :destroy  end    class Release < ApplicationRecord    has_many :discs, dependent: :destroy  end    class Disc < ApplicationRecord    has_many :sides, class_name: "DiscSide", dependent: :destroy  end    class DiscSide < ApplicationRecord    has_many :tracks, dependent: :destroy  end    class Track < ApplicationRecord    belongs_to :disc_side  end  

Post JSON body in rspec controller test in Rails 5

Posted: 15 Sep 2016 07:01 AM PDT

So I'm trying to create a controller test that posts the form data. I'm doing this because there is a bug in RSpec (or maybe it's Rails) right now where nested parameters aren't being processed correctly, so I'd like to just post the data in the body as JSON.

so if I have

post :create, format: :json, params: {        interview: {          name: 'NEW_INTERVIEW',          description: 'NEW_DESC'        },        questions: [          {            prompt: 'SA',            question_type: 'short_answer',            details: {}          },          {            prompt: 'LA',            question_type: 'long_answer',            details: {}          },          {            prompt: 'MC',            question_type: 'multiple_choice',            details: {              answer: 1,              choices: [                'Choice 1',                'Correct Choice',                'Another Choice'              ]            }          },          {            prompt: 'FU',            question_type: 'file_upload',            details: {}          },          {            prompt: 'CA',            question_type: 'code_area',            details: {}          }        ]      }  

Where params is a hash, it doesn't work since the parameters aren't getting processed correctly, you can try it out yourself but basically for some reason the details in the third question get put into the second question. I feel like if I can just pass the data directly as a JSON body though this bug won't come up since it's pretty hard to mess up parsing JSON.

CSS - text flow and centering

Posted: 15 Sep 2016 08:12 AM PDT

I'm building an events app using Rails. On my index page each event is represented by a relevant image upon which the event title and date are transposed upon it. Like this -

When titles are succinct...

Ideally, I would want a user to input a title for their event which is 'to the point'/ 'succinct' however there's no real way I can control this nor would I want to. When I try and input an overly long title this happens -

When titles are too long...

I need the text to flow and for the title (and date) to be absolutely centred in the middle of the image.At the moment its breaking (as shown below) and clinging to the left.This is my relevant code I have at the moment -

events.index.html.erb

<ul>                        <% @events.each do |event| %>                  <li class="events">                           <%= link_to (image_tag event.image.url), event, id: "image" %>                      <div class="text">                            <h2><%= link_to event.title, event %></h2>                          <h3><%= link_to event.date.strftime('%A, %d %b %Y'), event %></h3>                  </li>                             <% end %>                      </div>                </ul>         

events.css.scss

  li.events {       width: 350px;       height: 350px;       float: left;      margin: 20px;      list-style-type: none;      position: relative;     }    li.events img {       width: 100%;       height: 100%;       border-radius: 20px;            }    div.text  {           padding: 25px;       position: absolute;       top: 100px;      left: auto;        }    div.text a {      text-decoration: none;      color: #FF69B4;      font-weight: bolder;      padding: 5px;      border-radius: 10px;          background-color: rgba(255,255,255,.8);      -webkit-backdrop-filter: invert(10px);      margin: 0 auto;      text-align: center;      }  

I'm using the bootstrap gem but not sure whether this is relevant for this issue. Any assistance is appreciated.

Rails 3 Nested attributes get label and type dynamically

Posted: 15 Sep 2016 06:53 AM PDT

AppKey.rb

attr_accessible: :label, :key, :value, :default_value, :display_type  

AppKey Table

AppKeys(id: integer, label: string, key: string, value: integer, default_value: string, display_type: string)  

Example:

label: "Android Key", value: 1, default_value: "some key", display_type: "textarea"  

AndroidAppKeys.rb

attr_accessbile: :app_id, :name, :value  belongs_to :app  

AndroidAppKeys

AndroidAppKeys(id: integer, app_id:integer, name: integer, value: string, created_at: datetime, updated_at: datetime)  

Example:

app_id:1, name: 1, value: "entered by user", created_at: datetime, updated_at: datetime  

Name contains the reference of the of the AppKey table

App

(id:integer app_name:string dev_name:string)  

App.rb

has_many :android_app_keys  accepts_nested_attributes :android_app_keys  
  1. I want to create nested form that should dynamically get the label and display type from AppKey table and only "value" should be saved in AndroidAppKey table.

  2. Nested form should dynamically create field based on the display type.

example

category name: textfield  author name: textfield  Allow HTTP content: checkbox  

"display_type" will be mentioned in AppKey table.

PG::UniqueViolation: ERROR: duplicate key value violates unique constraint

Posted: 15 Sep 2016 06:53 AM PDT

I am using devise(4.2.0) in rails(4.2.6). In my appication i use nested attributes in user and profile table. I need to validate the password, only if i create the new record and the password field is not validate when i update the created records.

my user.rb file is

class User < ActiveRecord::Base   has_one :profile   has_one :company_profile   accepts_nested_attributes_for :profile   attr_accessor :profile_updation        devise :database_authenticatable, :registerable,          :recoverable, :rememberable, :trackable, :validatable     validates_presence_of :email, if: :email_required?        validates_presence_of :password, if: :password_required?   validates_confirmation_of :password, if: :password_required?      protected     def email_required?     true && profile_updation.blank?   end     def password_required?     !password.nil? || !password_confirmation.nil?       end    end

When i run my application this error is occurred.

PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_users_on_email" DETAIL: Key (email)=() already exists. : INSERT INTO "users" ("first_name", "last_name", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"

I searched this issue but i am not get a idea to solve it.

User & profile table in schemafile

create_table "users", force: :cascade do |t|     t.string   "email",                  default: "", null: false     t.string   "encrypted_password",     default: "", null: false     t.string   "reset_password_token"     t.datetime "reset_password_sent_at"     t.datetime "remember_created_at"     t.integer  "sign_in_count",          default: 0,  null: false     t.datetime "current_sign_in_at"     t.datetime "last_sign_in_at"     t.inet     "current_sign_in_ip"     t.inet     "last_sign_in_ip"     t.datetime "created_at",                          null: false     t.datetime "updated_at",                          null: false     t.string   "first_name"     t.string   "last_name"     t.string   "user_id"   end     add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree   add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree           add_index "profiles", ["user_id"], name: "index_profiles_on_user_id", using: :btree    create_table "profiles", force: :cascade do |t|     t.string   "company_name"     t.integer  "country"     t.integer  "state"     t.integer  "business"     t.string   "mobile_no"     t.datetime "created_at",       null: false     t.datetime "updated_at",       null: false     t.integer  "user_id"     t.boolean  "terms_conditions"   end

Can not create new user record on Rails api via Postman

Posted: 15 Sep 2016 07:28 AM PDT

I am creating new api app via Ruby on Rails. So i am using Devise to manage my users table.

The problem when i test the api by send the request via Postman, it can not passed my model validation.

So this is my controller

class UsersController < ApplicationController      respond_to :json      def create      user = User.new(user_params)      if user.save        render json: user, status: 201, location: [:my, user]      else        render json: { errors: user.errors }, status: 422      end    end      private      def user_params      params.require(:user).permit(:email, :password, :password_confirmation,:username,:fullname,:grade)    end    end  

This is the data that i send to server via Postman

{      "user"  : {          "email": "test5@gmail.com",          "password": "123456",          "password_confirmation": "123456",          "username": "yofoyf",          "fullname": "narotuo sarp",          "grade": "aaa"      }  }  

And i also set the header to be application/json like this

enter image description here

But when i click send i got errors because it can not pass my validation like this

Sign up    3 errors prohibited this user from being saved:    Username can't be blank  Grade can't be blank  Fullname can't be blank  

This is my model

class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable      validates :username, presence: true ,uniqueness: true    validates :grade, presence: true    validates :fullname, presence: true    end  

So how can i make the Postman works? It seems like the server cannot read my username, fullname and grade record.

Thanks!

How to handle object list request

Posted: 15 Sep 2016 06:41 AM PDT

I am trying to read a list of objects

[    {      "name" : "Jhone"      "age" : 25    },     {      "name" : "Chris"      "age" : 24    }  ]  

How to handle that types of request?

How to test disabled field in ruby on rails and assert_select?

Posted: 15 Sep 2016 06:19 AM PDT

I want to test presence of disabled field generated in rails(5) view helper

form_for(@metric) do |f|    f.text_field :type, disabled: true  end  

it creates HTML

<input id="metric_type" type="text" name="metric[type]" value="Gamfora::Metric::Point" disabled="disabled">  

It should be probably just

<input id="metric_type" type="text" name="metric[type]" value="Gamfora::Metric::Point" disabled>  

but it is OK and do the job.


In Firebug I verify that CSS selector is input#metric_type:disabled.

But when I use it in controller(+view) tests

assert_select "input#metric_type:disabled"  

I get error

RuntimeError: xmlXPathCompOpEval: function disabled not found  

Is there any way, how to test that input selected by ID is disabled?

An error occurred while installing pg (0.18.4), and Bundler cannot continue

Posted: 15 Sep 2016 05:56 AM PDT

I encounter the following error while running bundle install

Ruby 2.3 is installed but ruby 2.2.2 is being used through RVM - rvm use 2.2.2 but i dont think thats where the issue is

The issues are included below

jon220@jon220-XPS-12-9Q33:~/Desktop/em-client$ bundle install      Fetching gem metadata from https://rubygems.org/.............      Fetching version metadata from https://rubygems.org/...      Fetching dependency metadata from https://rubygems.org/..      Using rake 11.1.1      Using i18n 0.7.0      Using json 1.8.3      Using minitest 5.8.4      Using thread_safe 0.3.5      Using builder 3.2.2      Using erubis 2.7.0      Using mini_portile2 2.0.0      Using rack 1.6.4      Using mime-types 2.99.1      Using arel 6.0.3      Using bcrypt 3.1.11      Using coderay 1.1.1      Using debug_inspector 0.0.2      Using thor 0.19.1      Using bundler 1.13.1      Using concurrent-ruby 1.0.1      Using byebug 8.2.2      Using chronic 0.10.2      Using coffee-script-source 1.10.0      Using execjs 2.6.0      Using orm_adapter 0.5.0      Using multi_json 1.11.2      Using tilt 2.0.2      Using multi_xml 0.5.5      Using method_source 0.8.2      Installing pg 0.18.4 with native extensions      Using slop 3.6.0      Using puma 3.2.0      Using rails_serve_static_assets 0.0.5      Using rails_stdout_logging 0.0.4      Using sass 3.4.21      Using spring 1.6.4      Using sqlite3 1.3.11      Using rdoc 4.2.2      Using tzinfo 1.2.2      Using nokogiri 1.6.7.2      Using rack-test 0.6.3      Using warden 1.2.6      Using mail 2.6.3      Using better_errors 2.1.1      Using binding_of_caller 0.7.2      Using sprockets 3.5.2      Using whenever 0.9.7      Using coffee-script 2.4.1      Using uglifier 2.7.2      Using rollbar 2.12.0      Using httparty 0.13.7      Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        /home/jon220/.rvm/rubies/ruby-2.2.2/bin/ruby -r      ./siteconf20160915-12645-sijcbm.rb extconf.rb      checking for pg_config... no      No pg_config... trying anyway. If building fails, please try again with       --with-pg-config=/path/to/pg_config      checking for libpq-fe.h... no      Can't find the 'libpq-fe.h header      *** extconf.rb failed ***      Could not create Makefile due to some reason, probably lack of necessary      libraries and/or headers.  Check the mkmf.log file for more details.  You may      need configuration options.        Provided configuration options:          --with-opt-dir          --without-opt-dir          --with-opt-include          --without-opt-include=${opt-dir}/include          --with-opt-lib          --without-opt-lib=${opt-dir}/lib          --with-make-prog          --without-make-prog          --srcdir=.          --curdir          --ruby=/home/jon220/.rvm/rubies/ruby-2.2.2/bin/$(RUBY_BASE_NAME)          --with-pg          --without-pg          --enable-windows-cross          --disable-windows-cross          --with-pg-config          --without-pg-config          --with-pg_config          --without-pg_config          --with-pg-dir          --without-pg-dir          --with-pg-include          --without-pg-include=${pg-dir}/include          --with-pg-lib          --without-pg-lib=${pg-dir}/lib        extconf failed, exit code 1        Gem files will remain installed in      /home/jon220/.rvm/gems/ruby-2.2.2/gems/pg-0.18.4 for inspection.      Results logged to      /home/jon220/.rvm/gems/ruby-2.2.2/extensions/x86_64-linux/2.2.0/pg-0.18.4/gem_make.out        An error occurred while installing pg (0.18.4), and Bundler cannot      continue.      Make sure that `gem install pg -v '0.18.4'` succeeds before bundling.  

Any help would be greatly appreciated

Twilio - The requested resource not found error. when sending sms messages

Posted: 15 Sep 2016 05:41 AM PDT

When I send any message it gives an error.

Twilio::REST::RequestError: The requested resource /2010-04-01/Accounts/cafac01e41ad5fbad3da4ad8619c8d36/Messages.json was not found    # set up a client to talk to the Twilio REST API       @client = Twilio::REST::Client.new account_sid, auth_token       @client.account.messages.create({        :from => 'xxxxxx',         :to => 'xxxxxx',         :body => 'Twilio Testing',        })  

How to skip inner Rails realisation when debugging with Pry?

Posted: 15 Sep 2016 08:34 AM PDT

When we are debugging behaviour between different classes, sometimes Pry diving into inner Rails classes (like action_controller/metal/implicit_render.rb, active_support/callbacks.rb) or realisation of other plugins (for example New Relic).

What is the best way to skip this code and to debug only through your application code?

PS: help me please to make a proper title for this question if this one is not clear enough.

Updating rendered partial variable via ajax in Rails

Posted: 15 Sep 2016 05:56 AM PDT

I'm rendering a partial that contains a collection_select that uses a variable as a collection object.

Is there any way to update this variable via ajax?

How to post to multiple job boards from my job board - Ruby on Rails

Posted: 15 Sep 2016 05:22 AM PDT

I have been thinking about this question/topic for a while now and I have not been able to factor it programmatically on my Ruby on Rails Job Board.

What I like to do

I like to post job respectively to other free job boards upon checking a check_box when a job is created on my website.

Graphical explanation

This picture explains better what am hoping to achieve.

post on multiple job boards

What I think of doing

  • Find a public API that can post on multiple websites, or;
  • create rails methods that references those free job board's new action.

I will appreciate any direction into this. Be it using a particular gem, or code to factor this. Thanks.

No comments:

Post a Comment