Saturday, December 17, 2016

Mysql2::Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' | Fixed issues

Mysql2::Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' | Fixed issues


Mysql2::Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock'

Posted: 17 Dec 2016 07:45 AM PST

When running rake db:migrate, I get this error:

Mysql2::Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)


I've looked at other people's questions on here and none of their solutions have helped me, for example:

Solution One

mysql.server start

returns:

Starting MySQL . ERROR! The server quit without updating PID file (/usr/local/var/mysql/something.pid).

Solution Two

mysqladmin variables | grep socket

returns:

error: 'Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)' Check that mysqld is running and that the socket: '/tmp/mysql.sock' exists!


Further notes: I tried reinstalling mysql using homebrew, which was successful, and I'm still receiving the same errors:

Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

in ruby how do you do you map a nested hash tree but skipping the first element?

Posted: 17 Dec 2016 06:59 AM PST

I would like to ignore the first element of my hash tree as it has a different presentation and just map all elements minus the first one. This way my recursive function would work. So in my comments.map loop I would like to ignore the first element or delete it.

    def horizontal_tree_for(comments)          comments.map do |comment, nested_comments|             entry(comment) +             (nested_comments.size > 0 ?                          content_tag(:div, horizontal_tree_for(nested_comments), class: "branch") +              "</div>"              : "</div>")            end.join.html_safe    end    def entry(comment)      "<div class='entry'><span class='label'> #{comment.name} </span>"    end  

Can't migrate table with array

Posted: 17 Dec 2016 06:24 AM PST

When I try to migrate this:

class CreateTasks < ActiveRecord::Migration[5.0]    def change      create_table :tasks do |t|        t.string :category        t.string :text        t.string :asset_name        t.string :correct_answers, array:true, default: []        t.string :wrong_answers, array:true, default: []        t.integer :score          t.timestamps      end    end  end  

I get error:

== 20161217135738 CreateTasks: migrating ====================================== -- create_table(:tasks) rails aborted! StandardError: An error has occurred, this and all later migrations canceled:

can't quote Array

I am using rails 5 and mysql on development. Any idea how to solve that problem?

why "loop do" throws void value error?

Posted: 17 Dec 2016 07:48 AM PST

I'm using in my opinion trivial code, like this one

loop do         i++        break if i > 5    end   

but when I try to run I'll get void value expression break if i > 5

what am I doing wrong? What does this error mean?

"Missing `secret_key_base` for 'production' environment" error on Heroku

Posted: 17 Dec 2016 07:13 AM PST

I received the error "An unhandled lowlevel error occurred" when deploying my app for the first time on Heroku, and heroku logs shows:

Missing secret_key_base for 'production' environment, set this value in config/secrets.yml

1) The default secrets.yml specifies secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> for production

2) I generated a secret using rails secret, then added this to my app's Heroku config via heroku config:set SECRET_KEY_BASE='(the key)'

3) heroku config shows this value set for SECRET_KEY_BASE

4) Perhaps most importantly, based on older questions regarding this error, .gitignore does not include secrets.yml--it's the default .gitignore generated for a Rails 5 app. Therefore, secrets.yml should have been deployed with my app, which specifies that the secret be loaded via an environment variable in the production environment.

5) I've also run heroku ps:restart, in case the app needed some extra help for the environment variable setting to take effect

I read older posts, but the past answer seemed to be ensuring secrets.yml was not included in .gitignore, but as mentioned, this does not apply to the default Rails 5 .gitignore.

What else can I try? Thx.

Edit: When I set the config value at the command line, I also receive the Heroku message:

Setting SECRET_KEY_BASE and restarting (the app)... done

No route matches {:action=>"update", :controller=>"" - Rails 5

Posted: 17 Dec 2016 05:07 AM PST

I am getting the below error and unsure how to correct it - your help would be much appreciated.

when at a users show page, i do not get the error, but when at for example at any other page...such as the events index.html page the error displays

No route matches {:action=>"update", :controller=>"friendships", :friend_id=>#<User id: 5, email: "ian@gmail.com"  

expanded error in terminal

Started GET "/events" for ::1 at 2016-12-17 12:44:43 +0000  Processing by EventsController#index as HTML    User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 4]]    User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 4]]    User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."email" IS NULL LIMIT 1    Subscription Load (0.1ms)  SELECT  "subscriptions".* FROM "subscriptions" WHERE "subscriptions"."title" = ? LIMIT 1  [["title", "premium"]]    User Load (0.1ms)  SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users"."id" = "friendships"."friend_id" WHERE "friendships"."user_id" = ? AND "friendships"."status" = ?  [["user_id", 4], ["status", "requested"]]     (0.2ms)  SELECT COUNT(*) FROM "users" INNER JOIN "friendships" ON "users"."id" = "friendships"."friend_id" WHERE "friendships"."user_id" = ? AND "friendships"."status" = ?  [["user_id", 4], ["status", "requested"]]    Rendered shared/_content_dropdownbox_friendrequest.html.erb (4.8ms)    Rendered shared/_header.html.erb (10.7ms)    Rendered events/index.html.erb within layouts/application (11.8ms)  Completed 500 Internal Server Error in 23ms    ActionController::UrlGenerationError - No route matches {:action=>"update", :controller=>"friendships", :friend_id=>#<User id: 5, email: "ian@gmail.com", encrypted_password: "$2a$10$PMO5FPBzjjnFHI/ye8rfP.ONtHP3gagXomj1sbruBXH..."  

route file

Rails.application.routes.draw do      resources :friendships,   only: [:create, :update, :destroy]      devise_for :users    resources :users  end  

views/shared/_content_dropdownbox_friendrequest.html.erb

<ul>    <% current_user.requested_friends.each do |requester| %>      <li>        <%= link_to(image_tag(requester.image_url, :alt =>  "image", :class =>"#", id: ""), user_path(requester)) %>        <%= link_to truncate("#{requester.firstname} #{requester.lastname}", length: 23), user_path(requester) %>        <%= link_to 'Accept', friendship_path(user_id: current_user, friend_id: requester), controller: "friendships", action: "update", method: :put %>        <%= link_to 'Decline', friendship_path(user_id: current_user, friend_id: requester), controller: "friendships", action: "decline", method: :delete %>      </li>      <div class="clear"></div>    <% end %>  </ul>  

frienships_controller

class FriendshipsController < ApplicationController    before_action :authenticate_user!    before_filter :setup_friends      # Sends a friend request.    # We'd rather call this "request", but that's not allowed by Rails.    def create      Friendship.request(@user, @friend)      flash[:notice] = "Request sent."      redirect_to :back    end      # Accepts a friend request.    # We'd rather call this "accept", but that's not allowed by Rails.    def update      @user = User.friendly.find(params[:user_id])      @friend = User.friendly.find(params[:friend_id])      if @user.requested_friends.include?(@friend)        Friendship.accept(@user, @friend)        flash[:notice] = "Connection with #{@friend.firstname} accepted!"      else        flash[:notice] = "No connect request from #{@friend.firstname}."      end      redirect_to :back    end      def destroy      @user = User.friendly.find(params[:user_id])      @friend = User.friendly.find(params[:friend_id])      if @user.requested_friends.include?(@friend) #decline        Friendship.breakup(@user, @friend)        redirect_to :back      elsif @user.pending_friends.include?(@friend) #cancel        Friendship.breakup(@user, @friend)        redirect_to :back      elsif @user.friends.include?(@friend) #delete        Friendship.breakup(@user, @friend)        redirect_to :back      end    end      private    def setup_friends      @user = User.find(current_user.id)      @friend = User.find_by_email(params[:id])    end  end  

i am unsure how to solve the error, i tried something like the below but does not work:

<span>    <%= form_for friendship, url: friendship_path(requester), method: :put do |f| %>      <%= f.hidden_field :user_id, value: current_user.id %>      <%= f.hidden_field :friend_id, value: requester.id %>      <%= submit_tag "Accept_test", controller: "friendships", action: "update", class: "btn btn_add_friend" %>    <% end %>  </span>  

ObjectSpace.each_object(Foo).count

Posted: 17 Dec 2016 07:24 AM PST

I'am trying to figure out ObjectSpace.each_object
In console:

class Foo; end    Foo.new    ObjectSpace.each_object(Foo).count    => 1    GC.start    ObjectSpace.each_object(Foo).count    => 1   

I've seen examples and I know that the second count should be 0.
Any ideas what is going on here?
Thanks.

Rails 5: render partial in another partial with AJAX

Posted: 17 Dec 2016 04:25 AM PST

I'm a bit stuck in trying to implement AJAX where on "link_to" view is rendered and in that view I have another AJAX call.

I have menu sidebar where there is something like this:

<li class="<%= is_active_action('positions') %>"><%= link_to "Positions", positions_path, remote: true %></li>  

In application.html.erb I have this:

<!-- Main view  -->  <div id="yield">     <%= yield %>  </div>  

Actually not sure if this is the right way to do, but so far it worked.

Then in views/../positions/index.js.coffee I have this

$("#yield").empty()    .append("<%= escape_javascript(render 'inventory/positions/index') %>")  

which is redering /positions/_index.html.erb partial. In there I have <div id="media_list"> and <div id='positions_table'>

In assets/javascripts I have positions.coffee

$ ->  $(document).on 'change', '#media_list', (evt) ->      $.ajax 'update_positions',        type: 'GET'        dataType: 'script'        data: {          media_id: $("#media_list option:selected").val()        }        error: (jqXHR, textStatus, errorThrown) ->          console.log("AJAX Error: #{textStatus}")        success: (data, textStatus, jqXHR) ->          console.log("Dynamic media select OK!")  

This is basically listening to drop-down change and then passing media_id to controller, then this /views/../positions/update_positions.js.coffee renders second partial (/views/../positions/_positions.html.erb):

$("#positions_table").empty()    .append("<%= escape_javascript(render 'inventory/positions/positions', locals: {positions: @positions}) %>")  

At the moment on dropdown change I cannot make second partial (_positions.html.erb) to render. Any ideas what could be wrong? Thank you for any help.

How to use boolean with bootstrap nav-tabs?

Posted: 17 Dec 2016 04:29 AM PST

I'm trying to use tabs instead of a check_box.

This is what I had...

<%= f.check_box :someday %> Someday

This is what I'm in the process of changing it to...

<ul class="nav nav-tabs">    <li role="presentation" class="active"><a href="">Schedule</a></li>    <li role="presentation"><a href="">Someday</a></li>  </ul>  

How can I do it so that when the Someday tab is clicked then it would be the equivalent of checked and Schedule would be the equivalent of unchecked?

Bootstrap is already integrated with project.

Testing interaction requests sequences

Posted: 17 Dec 2016 07:34 AM PST

There best practices is do not use @instance variables and use let(:object). But how to write test of call sequences where each step require previous state but not clean state.

I'd like to write code like this:

describe "intearction" do    let(:user1) { ... }    let(:user2) { ... }      it "request" do      get "/api/v1/request", {user2}, token(user1)      expect(...).to ...    end      it "confirm" do      get "/api/v1/confirm", {user1}, token(user2)      expect(...).to ...    end  end  

But that will not work. It may be worked only like this:

describe "intearction" do    let(:user1) { ... }    let(:user2) { ... }      it "all tests" do      # request      get "/api/v1/request", {user2}, token(user1)      expect(...).to ...      # confirm      get "/api/v1/confirm", {user1}, token(user2)      expect(...).to ...    end  end  

The it become unusable and names of tests become comments or puts to console. The rspec subsystem loses its purpose. Using @instance variables is bad practice, is there any let-like definition function that does not create new plain variable per each test but per group of tests?

The sequences and api's exists not the first year. What is about your practice of testing sequences?

Rails is not updating file on the server

Posted: 17 Dec 2016 03:15 AM PST

I have _form partial for loading form content on the index page but I cannot update it with new code because it looks like Rails is not noticing any changes on the file. I tried to restart the server, cleared browser cache, checked application in Safari and Chrome, checked it in Incognito mode, tried to delete and make the same file again, checked this file twice in both Sublime Text and TextEdit but everything looks okay.

I checked this settings in config/environments/development.rb too:

config.cache_classes = false  config.consider_all_requests_local = true  config.action_controller.perform_caching = false  

But still nothing.

Rails: How to make nested form only do validation for the outside model?

Posted: 17 Dec 2016 03:00 AM PST

====== CODE =====
Model father.rb & son.rb

class Father < ApplicationRecord    has_many :sons    validates :f_name, presence: true    accepts_nested_attributes_for :sons  end    class Son < ApplicationRecord    belongs_to :father    validates :s_name, presence: true  end  

_form.html.erb--fathers

<%= form_for @order do |f| %>    <%= f.text_field :f_name %>    <%= f.fieid_for :sons do |ff| %>      <%= ff.s_name %>    <% end %>  <% end %>  

fathers_controller.rb

def create    @father = Father.new father_params    if @father.save      do_something    end  end  

======= QUESTION ======
If I save father object like below, it will do validations for both father and son.
Instead, if I change it to @father.save(validate: false), I think this will jump both validations. What I want is only to do validation for father's attribute. Is there a way to achieve this?

configuring controller tests with rails engines

Posted: 17 Dec 2016 02:58 AM PST

I'm trying to use the rails-controller-testing gem for an engine, but can't figure out how to change ::Rails::Controller::Testing constant not to get the uninitialized constant error. I installed the gem in the engine's gemspec (dealcms/engines/core/deal_core.gemspec).

dealcms/engines/core/spec/rails_helper.rb (This is from the config for simple rails 5 apps from rails-controller-testing docs.)

RSpec.configure do |config|    [:controller, :view, :request].each do |type|      config.include ::Rails::Controller::Testing::TestProcess, :type => type      config.include ::Rails::Controller::Testing::TemplateAssertions, :type => type      config.include ::Rails::Controller::Testing::Integration, :type => type    end  end  

My engine structure:

dealcms/engines/core/lib/deal/core/engine.rb

module Deal    module Core      class Engine < ::Rails::Engine        isolate_namespace Deal      end    end  end  

And my controllers can be found in the dealcms/engines/core/app/controllers/deal folder.

The model name 'Wta' was recognized as a plural, using the singular 'Wtum' instead

Posted: 17 Dec 2016 03:04 AM PST

I generated a model for Wta (women tennis association) and this is what happened:

asarluhi@home:~/workspace/tennis_project $ rails generate model Wta ranking:integer name:string points:integer  Running via Spring preloader in process 8875  [WARNING] The model name 'Wta' was recognized as a plural, using the singular 'Wtum' instead. Override with --force-plural or setup custom inflection rules for this noun before running the generator.        invoke  active_record        create    db/migrate/20161217102926_create_wta.rb        create    app/models/wtum.rb        invoke    test_unit        create      test/models/wtum_test.rb        create      test/fixtures/wta.yml  

So rails, without prompting me with a choice, solved what it perceived as an issue singularizing Wta into Wtum: that's horrible!
What choices am I now left with: changing all those files and inside code or deleting them by hand and re-generate the model with option --force-plural?

The difference of the Geocoder result and autocomplete

Posted: 17 Dec 2016 07:10 AM PST

I'm making the airbnb clone now. In this application I'm using geocoder gem and google autocomplete.

In the top page, there is a search form. In that form I'm using autocomplete and Geocoder.

When user select autocomplete field I get lat and lng from autocomplete.

When user doesn't select autocomplete suggestions, they get the lat and lng data from the Geocoder.coordinates.

The problem is when user selecet "Mariana bay sands singapore" in autocomplete, it returns the lat and lng params.

But user type the "Mariana bay sands singapore" in the search form (not select auto complete suggestions), it doesn't return the lat and lng params.

How can I get the lat and lng params like airbnb?

Sendmail 500 Internal Server Error(nginx + passenger + sinatra)

Posted: 17 Dec 2016 02:38 AM PST

I have following code for sending mails:

app.rb

post '/send' do    Pony.mail({      :to => 'mymail@gmail.com',      :from => params[:email],      :subject => params[:username],      :body => params[:message],      :via => :sendmail    })      content_type :json    {       :status =>'OK',      :data => {        :email => params[:email],        :name => params[:username],        :message => params[:message]      }    }.to_json  end  

On localhost mail is sent without errors. On server get error. In console web toll google chrome display: 500 Internal Server Error.

XHR display following information:

Request URL:https://namesite.org/send  Request Method:POST  Status Code:500 Internal Server Error  Remote Address:188.166.76.199:443  Response Headers  view source  Connection:keep-alive  Content-Length:30  Content-Type:text/html;charset=utf-8  Date:Sat, 17 Dec 2016 10:32:52 GMT  Server:nginx/1.10.1 + Phusion Passenger 5.0.30  Status:500 Internal Server Error  X-Content-Type-Options:nosniff  X-Frame-Options:SAMEORIGIN  X-Powered-By:Phusion Passenger 5.0.30  X-XSS-Protection:1; mode=block  

Error_log from Nginx:

91.219.222.29 - - [17/Dec/2016:10:30:33 +0000] "GET /js/ext/filesaver.min.js HTTP/1.1" 200 5118 0.0026  App 10472 stderr: 109.162.90.123 - - [17/Dec/2016:10:30:41 +0000] "GET / HTTP/1.1" 200 21195 0.0081  App 10472 stderr: 2016-12-17 10:32:52 - Errno::ENOENT - No such file or directory - which:  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/pony-1.11/lib/pony.rb:332:in ``'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/pony-1.11/lib/pony.rb:332:in `sendmail_binary'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/pony-1.11/lib/pony.rb:163:in `mail'  App 10472 stderr:   /home/deploy/sudoku/releases/20161217094256/app.rb:180:in `block in <top (required)>'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1611:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1611:in `block in compile!'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:975:in `block (3 levels) in route!'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:994:in `route_eval'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:975:in `block (2 levels) in route!'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1015:in `block in process_route'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1013:in `catch'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1013:in `process_route'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:973:in `block in route!'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:972:in `each'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:972:in `route!'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1085:in `block in dispatch!'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1067:in `block in invoke'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1067:in `catch'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1067:in `invoke'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1082:in `dispatch!'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:907:in `block in call!'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1067:in `block in invoke'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1067:in `catch'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1067:in `invoke'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:907:in `call!'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:895:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-protection-1.5.3/lib/rack/protection/xss_header.rb:18:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-protection-1.5.3/lib/rack/protection/base.rb:49:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-protection-1.5.3/lib/rack/protection/base.rb:49:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-protection-1.5.3/lib/rack/protection/path_traversal.rb:16:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-protection-1.5.3/lib/rack/protection/json_csrf.rb:18:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-protection-1.5.3/lib/rack/protection/base.rb:49:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-protection-1.5.3/lib/rack/protection/base.rb:49:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-protection-1.5.3/lib/rack/protection/frame_options.rb:31:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-1.6.5/lib/rack/session/abstract/id.rb:225:in `context'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-1.6.5/lib/rack/session/abstract/id.rb:220:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-1.6.5/lib/rack/logger.rb:15:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-1.6.5/lib/rack/commonlogger.rb:33:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:219:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:212:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-1.6.5/lib/rack/head.rb:13:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rack-1.6.5/lib/rack/methodoverride.rb:22:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:182:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:2013:in `call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1487:in `block in call'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1787:in `synchronize'  App 10472 stderr:   /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1487:in `call'  App 10472 stderr:   /usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:97:in `process_request'  App 10472 stderr:   /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:160:in `accept_and_process_next_request'  App 10472 stderr:   /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:113:in `main_loop'  App 10472 stderr:   /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler.rb:416:in `block (3 levels) in start_threads'  App 10472 stderr:   /usr/lib/ruby/vendor_ruby/phusion_passenger/utils.rb:113:in `block in create_thread_and_abort_on_exception'  App 10472 stderr:   App 10472 stderr: 91.149.153.167 - - [17/Dec/2016:10:32:52 +0000] "POST /send HTTP/1.1" 500 30 0.0055  [ 2016-12-17 10:35:33.5374 10448/7fbfe2c0c700 age/Cor/CoreMain.cpp:819 ]: Checking whether to disconnect long-running connections for process 11788, application /home/deploy/sudoku/current/public  [ 2016-12-17 10:35:33.8592 10448/7fbfe2c0c700 age/Cor/CoreMain.cpp:819 ]: Checking whether to disconnect long-running connections for process 11799, application /home/deploy/sudoku/current/public  

How to fetch those records whose due date is 3 more days more from the current date in rails?

Posted: 17 Dec 2016 02:12 AM PST

I am trying to query the records whose due_date(datetime datatype) is 3 more days greater than the current day. i want to send the remainder mails to the people before 3 days of their due date. for that i am writing this query.

remind_invoices = Invoice.where("status = ? AND (due_date - 3) == ?", "unpaid", Date.today )  

similarly i want to send the remainder mails saying your due date is over, (in this case due date is past date.) i want to fetch those records for those if we add 3 days it shoud be equal to current day. in simple words i want to send emails after the 3 days of their due date is over. for this my current query is this.

 unpaid_invoices = Invoice.where("status = ? AND (due_date + 3) == ?", "unpaid", Date.today )  

but these queries are giving errors like

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '== '2016-12-17')' at line 1: SELECT `invoises`.* FROM `invoises`  WHERE (status = 'unpaid' AND (due_date - 3) == '2016-12-17')  ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '== '2016-12-17')' at line 1: SELECT `invoises`.* FROM `invoises`  WHERE (status = 'unpaid' AND (due_date - 3) == '2016-12-17')  

Rails 5 - Acts as Taggable On - is this gem deprecated?

Posted: 17 Dec 2016 12:57 AM PST

I have been trying all year to learn how to use the Acts as Taggable On gem.

The tutorials are very old and out of date. The issues I've opened on the gem documentation have been ignored.

These two posts are my most recent posts looking for help - here and here. I've seen others with similar questions not get any responses to those questions either.

Someone on codementor.io offered a paid session to show me how to build my own solution - suggesting that its necessary because the gem is out of date. Is this correct?

So - is that because there is another way to do this instead of using the gem?

I found this site point tutorial - but before I try to build my own tagging system - is there something obvious for why Acts as Taggable On is no longer supported?

how to insert data to manytomany model in Django serialize (ValueError )

Posted: 17 Dec 2016 01:39 AM PST

I have created two model one is called Company and CompanyHasAddressType . Company model include company name and CompanyHasAddressType include other info about company so when I insert data to this two model by one API I got below error . This model has OneToMany Relationship

Cannot assign OrderedDict([(u'name', u'Lahiru'), (u'note', u'dsad'), (u'companycol', u'jygfjhj')]): CompanyHasAddressTypre.company must be a "Company" instance.

Filterrific gem is not refreshing or filtering my table as expected

Posted: 16 Dec 2016 11:27 PM PST

I am a relative novice with rails and I am trying to use the filterrific gem for some filtering. Basically I have the index page that shows a list of vendors and I want to be able to use the filtering to actively filter/sort the records. I was able to get through the tutorial and got through all of the errors, but for some reason when you enter data into the forms, nothing happens. It is not refreshing the view at all. Any thoughts on what I am doing wrong?

Vendor Model:

    filterrific(          default_filter_params: { sorted_by: 'created_at_desc' },          available_filters: [            :sorted_by,            :search_query,            :with_vendor_type_id,            :with_created_at_gte          ]        )        scope :search_query, lambda { |query|          return nil  if query.blank?        terms = query.downcase.split(/\s+/)          terms = terms.map { |e|          (e.gsub('*', '%') + '%').gsub(/%+/, '%')        }          num_or_conds = 2        where(          terms.map { |term|            "(LOWER(vendors.name) LIKE ? OR LOWER(vendors.bio) LIKE ?)"          }.join(' AND '),          *terms.map { |e| [e] * num_or_conds }.flatten        )      }        scope :sorted_by, lambda { |sort_option|      direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'        case sort_option.to_s        when /^created_at_/          order("vendors.created_at #{ direction }")        when /^name_/          order("LOWER(vendors.name) #{ direction }, LOWER(students.bio) #{ direction }")        when /^vendor_type_title_/          order("LOWER(vnedor_types.title) #{ direction }").includes(:vendor_type)        else          raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")        end      }        scope :with_vendor_type_id, lambda { |vendor_type_ids|        where(with_vendor_type_id: [*vendor_type_ids])      }        scope :created_at_gte, lambda { |reference_time|        where('vendors.created_at >= ?', reference_time)      }        def self.options_for_sorted_by      [        ['Name (a-z)', 'name_asc'],        ['Registration date (newest first)', 'created_at_desc'],        ['Registration date (oldest first)', 'created_at_asc'],        ['Type(a-z)', 'vendor_type_id_asc']      ]    end  

My Vendor Controller

 def index        @filterrific = initialize_filterrific(        Vendor,        params[:filterrific],        select_options: {          sorted_by: Vendor.options_for_sorted_by,          with_vendor_type_id: VendorType.options_for_select        },        persistence_id: 'shared_key',        default_filter_params: {},        available_filters: [],      ) or return        @vendors = @filterrific.find.page(params[:page])        # Respond to html for initial page load and to js for AJAX filter updates.      respond_to do |format|        format.html        format.js      end      rescue ActiveRecord::RecordNotFound => e      puts "Had to reset filterrific params: #{ e.message }"      redirect_to(reset_filterrific_url(format: :html)) and return    end  

My Index View

<h1>Vendors</h1>    <%= form_for_filterrific @filterrific do |f| %>    <div>      Search      <%= f.text_field(        :search_query,        class: 'filterrific-periodically-observed'      ) %>    </div>    <div>      Vendor Type      <%= f.select(        :with_vendor_type_id,        @filterrific.select_options[:with_vendor_type_id],        { include_blank: '- Any -' }      ) %>    </div>    <div>      Registered after      <%= f.text_field(:with_created_at_gte, class: 'js-datepicker') %>    </div>    <div>      Sorted by      <%= f.select(:sorted_by, @filterrific.select_options[:sorted_by]) %>    </div>    <div>      <%= link_to(        'Reset filters',        reset_filterrific_url,      ) %>    </div>  <% end %>    <%= render(    partial: 'vendors/list',    locals: { vendors: @vendors }  ) %>  

My Partial

<div id="filterrific_results">      <div>      <%= page_entries_info vendors %>    </div>      <table>      <tr>        <th>Name</th>        <th>User ID</th>        <th>Country</th>        <th>Registered at</th>      </tr>      <% vendors.each do |vendor| %>        <tr>          <td><%= link_to(vendor.name, vendor_path(vendor)) %></td>          <td><%= vendor.user_id %></td>          <td><%= vendor.vendor_type %></td>          <td><%= vendor.created_at %></td>        </tr>      <% end %>    </table>  </div>    <%= will_paginate vendors %>  

The JS file

<%# app/views/vendor/index.js.erb %>  <% js = escape_javascript(    render(partial: 'vendors/list', locals: { vendors: @vendors })  ) %>  $("#filterrific_results").html("<%= js %>");  

I got to the point where the from renders and got past all of the error messages, but its just not actually doing the filtering.

How can I store a Json responce in database in ruby on rails

Posted: 17 Dec 2016 07:23 AM PST

How can I store the json response which I am getting form api into my database. Here is what I want to do the responce from API:

[    {      "tag_id": "1",      "tag_name": "FCC",      "group_id": "15",      "object_type_id": "0"    },    {      "tag_id": "2",      "tag_name": "SWA Buyers",      "group_id": "15",      "object_type_id": "0"    },    {      "tag_id": "3",      "tag_name": "SWA Nonbuyers",      "group_id": "15",      "object_type_id": "0"    }  ]  

Now I want to store all the info in my table

How to use one foreign key for two models in Ruby on Rails?

Posted: 16 Dec 2016 11:37 PM PST

Here is my migration file

class CreateTestRevisions < ActiveRecord::Migration    def change      create_table :test_revisions do |t|        t.integer :user_id        t.integer :test_id        t.integer :question_id        t.integer :test_type        t.timestamps null: false      end    end  end  

I have two models: OnlineTest & AllindiaTest.

How can I relate the t.integer :test_id to these two models?

Getting Elixir Efficiency in Ruby [on hold]

Posted: 17 Dec 2016 04:35 AM PST

It's not kind of question but an interesting problem.

I have written a snippet in Elixir Phoenix to do some HTTP requests.

  defp request_from_seaweedfs(url, type, attribute) do      with {:ok, response} <- HTTPoison.get(url, [], []),           %HTTPoison.Response{status_code: 200, body: body} <- response,           {:ok, data} <- Poison.decode(body),           true <- is_list(data[type]) do        Enum.map(data[type], fn(item) -> item[attribute] end)      else        _ -> []      end    end  

The urls which am passing giving me back response in particular pattern as

        {"Directory":"/ballymore-project-wave/snapshots/recordings/2016/10/24/",  "Files":null,"Subdirectories":  [{"Name":"02","Id":1118240},{"Name":"17","Id":1122126},  {"Name":"03","Id":1118526},{"Name":"05","Id":1118979},{"Name":"07","Id":1119427},{"Name":"21","Id":1123207},      {"Name":"22","Id":1123400},{"Name":"23","Id":1123669},{"Name":"00","Id":1117610},{"Name":"01","Id":1117988},      {"Name":"15","Id":1121760},{"Name":"16","Id":1121914},      {"Name":"11","Id":1120635},{"Name":"14","Id":1121343},      {"Name":"12","Id":1120866},{"Name":"13","Id":1121209},      {"Name":"19","Id":1122742},{"Name":"20","Id":1122850},{"Name":"06","Id":1119163},{"Name":"08","Id":1119789}]}  

so I do as request_from_seaweedfs(url_day, "Subdirectories", "Name")

And I get the values of Name and This code works very efficiently in Phoenix, And I want to achieve the same thing in Rails. I know how to send HTTP request in Rails but I don't really know how to create something exactly the same. Sorry in advance if you find the question Off Topic.

Rails 5- How to import data from an xls file to the database

Posted: 17 Dec 2016 12:58 AM PST

I am trying to figure out how to add data from an xls file to my rails 5 psql database.

I have tried to follow the GoRails tutorials - but those become irrelevant quickly, because they use CSV files created somewhere in the app to do the tutorial. I don't know how to convert my xls data to csv data to follow along with that tutorial.

I have also tried each of these tutorials. I can't get any of them to work.

I have tried this tutorial, and this one, and this one. I can't get any of them to work.

The response to a question I posted on the blog for the first tutorial says to take a step not outlined in the post. It's not at all obvious to me that I'm supposed to fill in the gaps in the step by step instructions.

I outlined my attempts to get this working in this SO post. I wasn't able to find help to get the xls upload working. So, I'm setting out a request for help again - given the the first SO post became very long, with all the various attempts that I made to implement the suggested solutions.

I have:

class Randd::Field < ApplicationRecord        require 'csv'        # def self.import(file)    #     CSV.foreach(file.path, headers: true) do | row |    #         Randd::Field.create! row.to_hash    #     end    # end      def self.create(file)      CSV.foreach(file.path, headers: true) do |row|          randd_field_hash = row.to_hash # exclude the price field        randd_field = Randd::Field.where(id: randd_field_hash["id"])          if randd_field.count == 1          randd_field.first.update_attributes(randd_field_hash)        else          Randd::Field.create! row.to_hash#(randd_field_hash)        end # end if !product.nil?      end # end CSV.foreach    end # end self.import(file)  

First hunch: in this model, I'm requiring 'csv'. Do I have to require 'xls' or something else given that I don't actually have a list of comma separated values anywhere to import?

Routes.rb

namespace :randd do      resources :fields do        collection do          post :create        end      end    end  

Controller:

class Randd::FieldsController < ApplicationController    def index      @randd_fields = Randd::Field.all  end    def new      @field = Randd::Field.new  end    def create      # @field = Randd::Field.new(randd_field_params)      Randd::Field.create(params[:randd_field][:file])      redirect_to action: "index", notice: "Data imported"  end    def show      redirect_to action: "index"  end  

Index view:

  <table class="table table-bordered">      <tr>        <td> <h5>Title</h5> </td>        <td> <h5>Reference (ANZ)</h5> </td>        <td> <h5>Added</h5> </td>         <%# if policy(@package_ips).update? %>           <td> <h5>Manage this asset</h5></td>        <%# end %>        </tr>        <% @randd_fields.each do | field | %>          <td> <%= field.title %> </td>          <td> <%= field.anz_reference %> </td>          <td> <%= field.created_at.try(:strftime, '%e %B %Y') %> </td>        <% end %>      </tr>    </table>  

The commented components shown above show all the various options I tried to use to get this to work.

# def import  #   # byebug  #   # Randd::Field.import(params[:file])  #   # Randd::Field.create(params[:randd_field]['file'])  #   # redirect_to action: "index", notice: "Data imported"  # end    private   def randd_field_params    params.fetch(:randd_field, {}).permit(:title, :anz_reference)   end    end  

My form has:

<%#= simple_form_for (@field), multipart: true do |f| %>  <%= simple_form_for @field,  multipart: true do |f| %>    <%= f.error_notification %>      <div class="form-inputs" style="margin-bottom: 50px">      <div class="row">        <div class="col-md-12">          <div class="form_title">Research Field Codes</div>        </div>      </div>        <div class="row">        <div class="col-md-12">          <%= f.file_field :file %>        </div>      </div>    </div>      <div class="row">      <div class="col-md-10 col-md-offset-1" style="margin-top: 50px">        <div class="form-actions">          <%= f.button :submit %>        </div>      </div>    </div>  <% end %>  

The error message that arises out of this attempt says:

NoMethodError - undefined method `[]' for nil:NilClass:    app/controllers/randd/fields_controller.rb:13:in `create'  

Line 13 of my create action says:

Randd::Field.create(params[:randd_field][:file])  

Next hunch: my resources are nested. Randd is the top level and field is the child.

The model is called:

class Randd::Field < ApplicationRecord  

The controller is called:

class Randd::FieldsController < ApplicationController  

The permitted params in the controller are defined as:

  params.fetch(:randd_field, {}).permit(:title, :anz_reference)  

The form uses this opening line:

<%= simple_form_for @field,  multipart: true do |f| %>  

The line which is highlighted in the error message has:

Randd::Field.create(params[:randd_field][:file])  

I wonder if the problem has something to do with using randd_field in some of these places and just @field in the form? The form doesnt work if I try to change it to @randd_field and I don't know where to find the ruby or rails rules for how to use namespaces in any complete, accurate form.

Can anyone help to see what's wrong here? Alternatively does anyone have a reference to a complete tutorial that doesn't rely on me guessing what the missing steps are or how to convert it for use with xls instead of a .csv file?

Highlight text in a view to save it or tag it

Posted: 16 Dec 2016 11:20 PM PST

I'd like to add a functionality in some of my app views that would work like this: The user can select/highlight a portion of the text displayed > a tooltip on top of the selection will give the option of saving the selection > the portion of the text that was saved will become available in another view (let's call it the Saved Text View).

I could go about it using the JS's Selection object and calling a Create action through Ajax, when clicking the tooltip, so a new object containing the text selection is saved in the database. However, the data is already in the database and I need to be able to refer back to the original object where the saved string comes from.

So I was thinking on recording from the view via JS:

  1. The start and end of the selection
  2. Some data that let me find the original object where the text comes from in my rails database

This way I could use those references to tell Rails to select a particular object from the db and render a portion of the text contained on it in the Saved Text View.

I'm struggling to determine the best approach to achieve point 2. I was thinking maybe finding the object with a db query that looks for the content of the substring in a Model like:

Model.where("models.keywords ~= ?", 'theSelectedSubtring')  

But wondering if you know more efficient solutions or JS and Rails tools that can make this easier.

CSS z-index behaving strangely in my Rails 5 application

Posted: 16 Dec 2016 08:56 PM PST

I am using Rails 5 with SASS + Bootstrap and I have the following CSS code:

@import url('https://fonts.googleapis.com/css?family=Dancing+Script');  @import url('https://fonts.googleapis.com/css?family=Montserrat');    body {      background: #fff image-url('noise.png');      div.site-top {        position: fixed;      width: 100%;      height: 178px;      background: #fff image-url('logo01.jpg') no-repeat;      -webkit-box-shadow: 0px 5px 3px 0px rgba(50, 50, 50, 0.75);      -moz-box-shadow:    0px 5px 3px 0px rgba(50, 50, 50, 0.75);      box-shadow:         0px 5px 3px 0px rgba(50, 50, 50, 0.75);        div.main-title {          padding: 0px 0px 0px 290px;        font-family: 'Dancing Script';        font-size: 60px;        font-weight: bold;        color: #fccf00;        text-shadow: 3px 3px 2px rgba(150, 150, 150, 1);          div.secondary-title {            margin-top: -17px;          padding: 0px 0px 0px 35px;          font-family: 'Montserrat';          font-size: 22px;          font-weight: bold;          color: #49840c;          text-shadow: 0px 0px 0px rgba(150, 150, 150, 1);          }        }        div.top-menu {          margin: 25px 0px 0px 0px;        text-align: right;          height: 54px;          ul {            margin: 0px 47.5px 0px 47.5px;          padding: 0px 0px 0px 0px;            li {                float: right;            list-style-type: none;            padding: 15px 40px 14px 0px;              a {                color: #666;              font-size: 18px;              font-weight: bold;              }              a:hover {                text-decoration: none;              color: #333;              }            }          }        }      }      div.container {        z-index: -5;        div.site-body {          padding: 198px 20px 140px 20px;        background-color: #fff;          div.woman-from-fifties {            float: left;          height: 350px;          background: #fff image-url('wff2.jpg') no-repeat;          }        }      }    }  

which works with this app/views/layouts/application.html.erb

<!DOCTYPE html>  <html>    <head>      <title>Clean House Serviços Domésticos</title>      <%= csrf_meta_tags %>      <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>      <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>    </head>    <body>      <div class="site-top">        <div class="main-title">          Clean House          <div class="secondary-title">            Serviços Domésticos          </div>        </div>        <div class="top-menu">          <ul>            <li><a href="/clientes">Clientes</a></li>                    <li><a href="/fale_conosco">Fale conosco</a></li>                    <li><a href="/localizacao">Localização</a></li>                    <li><a href="/sobre_nos">Sobre nós</a></li>                    <li><a href="/">Homepage</a></li>          </ul>        </div>      </div>        <div class="container">        <div class="site-body clearfix">          <div class="site-content">            <%= yield %>          </div>        </div>      </div>    </body>  </html>  

and this app/views/website/index.html.erb

<div class="col-md-4 woman-from-fifties">  </div>  <div class="col-md-8">    <div class="well">      teste    </div>  </div>  

to generate a page like in this image

enter image description here

It all works fine until I scrool down the page and see the Bootstrap wells in the lower part, which has z-index: -5 as you may see, end up covering my upper banner as you may see in this image:

enter image description here

I really don't understand what is happening. As far as I am concerned, all elements inserted in this area with z-index: -5 should be below the upper part.

Could someone explain what am I doing wrong?

How do I generate an in-line, client side warning in rails 4

Posted: 17 Dec 2016 01:07 AM PST

There's plenty of ways to generate client side errors that prevent the user from saving form data, however, I want to allow the user to continue and save if they wish. I still want a message to pop up saying the data is suspect but if the user chooses, they can continue and save the data. What's the best way of doing this in rails 4?

Replace Nil Values before_save Rails

Posted: 16 Dec 2016 07:58 PM PST

I have a json file that I'm importing into my Rails DB.

JSON:

{   "data": [{     "title": "foo",     "color": "bar",     "size" : "baz",     "occupation" : "engineer",     "location" : "dallas",     "car" : "tesla",     "married" : true,     "dogs" : 4,     "food" : "tacos"     }]  

Now lets say "title" is not listed in one of the samples and it's stored as nil. I know I can update this with before_save in the model

Class Person    before_save :replace_nil_values      private      def replace_nil_values      self.title = "Not Listed" if title == nil    end  end  

This works. The problem is what happens if multiple properties are missing or listed as nil? I feel doing this would be super inefficient:

def replace_nil_values    self.title = "Not Listed" if title == nil    self.color= "Not Listed" if color == nil    self.size = "Not Listed" if size == nil    self.occupation = "Not Listed" if occupation == nil    self.location = "Not Listed" if location == nil    self.car = "Not Listed" if car == nil  end  

Is there a more efficient way of doing this?

Thanks

Add to has_many through association without finding objects

Posted: 16 Dec 2016 09:39 PM PST

Here is a typical has_many :through association:

class Physician < ApplicationRecord    has_many :appointments    has_many :patients, through: :appointments  end    class Appointment < ApplicationRecord    belongs_to :physician    belongs_to :patient  end    class Patient < ApplicationRecord    has_many :appointments    has_many :physicians, through: :appointments  end  

The Problem

The physician makes 4 appointments with patients: [1, 2, 3, 4]

I can add by finding the users:

user_ids = [1, 2, 3, 4]  users = User.where(id: user_ids)  @physician.patients.push(users)  

But I want to add by ID directly:

user_ids = [1, 2, 3, 4]  @physician.patients.push(user_ids)  

Rails: can one modify date attribute in model by callback? E.g.: Date.current + 1 (d + other)

Posted: 16 Dec 2016 08:01 PM PST

I have a table column - valid_to, which should represent a date: 30 days from the time the entry was saved into database. But how can I do such a thing in model? E.g. in controller I can do such thing this way:

@baby = baby.create(baby_params.          merge( :valid_to => DateTime.current + 30 )  

In view I can use hidden field in the form:

<%= f.hidden_field :valid_to => DateTime.current + 30 %>  

so is there a way to do such a thing in model? I tried defining self.valid_to before_validation but for no avail: in irb my valid_to column is just nil. To add: I store it as datetime not string.

No comments:

Post a Comment