Tuesday, July 5, 2016

Set default value of date_field only if current value is empty | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

Set default value of date_field only if current value is empty | Fixed issues


Set default value of date_field only if current value is empty

Posted: 05 Jul 2016 07:47 AM PDT

I'm using the same form in a partial to both create a new object and modify it. I have the following field:

<%= f.date_field :dob, class: 'form-control' %>  

I know that I can set its default by adding value: Time.now.strftime('%Y-%m-%d'), but I want to do this if and only if the current value is empty. How do I do that?

PG::ConnectionBad error while trying to run sidekiq server on a rails app on Windows

Posted: 05 Jul 2016 07:45 AM PDT

I am using windows. Here is the error I get while starting up the sidekiq server -

PG::ConnectionBad: timeout expired C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/sequel-4.36.0/lib/sequel/adapters/postgres.rb:243:in 'initialize' C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/sequel-4.36.0/lib/sequel/adapters/postgres.rb:243:in 'new' C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/sequel-4.36.0/lib/sequel/adapters/postgres.rb:243:in 'connect'

I checked the Postgress server logs on aws and it says 7

[12826]:LOG: could not accept SSL connection: Connection reset by peer"

gemfile is using sequel, sequel_pg..

same database connection works fine on another rails app without sidekiq..

How to make hash/array of params out of several selects?

Posted: 05 Jul 2016 07:23 AM PDT

I have two select dropdowns and when a user selects an option from each of them It has to group them in the following manner:

job =>    {      "types" => [1,2,3]    }  

or at least like this:

job => {    "types" => { "first" => "1", "second" => "2" }  }  

Is this possible to do in Rails?

For example, this example only sends the last select value:

<%= simple_form_for @job, url: jobs_path do |f| %>      <% 2.times do %>      <%= f.input :types, as: :select, collection: @types %>    <% end %>    <% end %>  

params hash problems with a hidden form post request

Posted: 05 Jul 2016 07:36 AM PDT

I have this hidden form:

<form action="/event_signup" method="post">      <input type="hidden" name="user_id" value="<%= session[:current_user]%>">      <input type="hidden" name="event_id" value="<%= event.id%>">      <input type="hidden" name="authenticity_token" value="<%= form_authenticity_token%>">      <input type="submit" value="Sign up">  </form>  

this is my event_attendances controller:

class EventAttendancesController < ApplicationController      def create          @event_attendance = EventAttendance.new(attendance_params)          if @event_attendance.save              flash[:success] = "Signed up for event successfully"          else              flash[:danger] = "An error occured whilst trying to sign you up for an event"          end          redirect_to root_url      end        private          def attendance_params              params.require(:event_attendance).permit(:event_id, :user_id)          end  end  

my route is set up as so:

post 'event_signup' => 'event_attendances#create'  

however I get an error when I click the submit form button:

ActionController::ParameterMissing in EventAttendancesController#create   

and when I try and see my params hash in the console I receive a name error:

NameError: undefined local variable or method `params'  

But I can see on the error page that my params hash is looking as it should:

Request    Parameters:    {"user_id"=>"1",  "event_id"=>"1",  "authenticity_token"=>"FskE5u1cxfN4JklMfM/JqKtg3t45tyP1z6ivUVmyLx+zlY7aShQDn+eF6aoOXp/StH6svsawXVtSCZcfe4UcsQ=="}  

And here is my event attendance model:

class EventAttendance < ActiveRecord::Base      belongs_to :user      belongs_to :event  end  

rake db:migrate error: db_development.locations' doesn't exist: SHOW FULL FIELDS FROM `locations`

Posted: 05 Jul 2016 07:35 AM PDT

database.yml

development:    adapter: mysql2    encoding: utf8    reconnect: false    database: db_development    username: root    password: "123"     socket: /var/run/mysqld/mysqld.sock    # Warning: The database defined as "test" will be erased and  # re-generated from your development database when you run "rake".  # Do not set this db to the same as development or production.  test:    adapter: mysql2    encoding: utf8    reconnect: false    database: db_test    pool: 5    username: root    password: "123"     socket: /var/run/mysqld/mysqld.sock    production:    adapter: mysql2    encoding: utf8    reconnect: false    database: db_production    pool: 5    username: root    password: "123"    socket: /var/run/mysqld/mysqld.sock  

I installed gem mysql2

I created database in mysql console.

After run rake db:migrate and display error: db_development.locations' doesn't exist: SHOW FULL FIELDS FROM locations

one migration from migrations:

class CreateLocations < ActiveRecord::Migration    def self.up      create_table :locations do |t|        t.string :name        t.string :type        t.integer :parent_id        t.integer :position          t.timestamps      end    end      def self.down      drop_table :locations    end  end  

What wrong and how solve this problem?

Rails New Article Error... Router error?

Posted: 05 Jul 2016 07:31 AM PDT

When opening the url http://localhost:3000/articles/new , the html.erb file I created for that link does not appear. The only page that appears is the default rails home page. How do I fix this to access articles/new file?

default rails page

Rails view javascript not loading

Posted: 05 Jul 2016 07:03 AM PDT

I'm currently trying to code a quiz for my rails app on c9 using js but the js doesn't seem to being loaded into the view file. Can anybody tell me what is wrong or suggest a fix?

The home page with the quiz start on it:

<div class = "signinstyle">    <div class = "row">          <div id="wrapAll">          <div id="wrapper">                    <img id="logo" src="img/geek.png" alt=""><br>                   <h1>Help us recommend a <span>Course</span></h1>                     </div>                   </div>                   </div>                   <div class ="row">                      <div id="wrapper">                  <input class="start-btn" type="submit" value="Start!" onclick="redirect('ques.html')">            </div>      </div>        </div>          <script src='main.js' type='text/javascript'></script>  

The view which is supposed to pull the questions from the js:

    <!--Functionality of recommender?? -->       <% provide(:title, '') %>          <!--containers for design/layout -->       <div class = "signinstyle">        <div class = "row">          <!--Page information -->               <div id="wrapAll">              <div id="wrapper">                        <div class="ques-wrap">                          <h2 id="ques">This is question</h2>                          <input class="btn1" type="submit" id="opt1" value="Option 1" onclick="optionClick('1')">                          <input class="btn2" type="submit" id="opt2" value="Option 2" onclick="optionClick('0')">                          <div class="clear"></div>                    </div>              </div>          </div>            </div>          </div>          <script src='main.js' type='text/javascript'></script>          <script type='text/javascript'>              window.onload = function(){                generate();              };          </script>  

The application layout view:

<!DOCTYPE html>  <html>  <head>    <meta charset="utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1">      <title><%= yield(:title) %> | Uni2choose</title>      <%= javascript_include_tag "https://www.google.com/jsapi", "chartkick" %>    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true  %>    <%= csrf_meta_tags %>    </head>  <body>      <%= render 'layouts/navbar' %>    <%= render 'layouts/header' %>    <br><br><br><br>          <% flash.each do |message_type, message| %>          <div class="alert alert-<%= message_type %>"><%= message %></div>        <% end %>            <%= yield %>          <%= render 'layouts/footer' %>  </body>            </html>  

The main.js file:

//= require jquery  //= require jquery_ujs  //= require bootstrap  //= require chartkick  //= require turbolinks  //= require_tree .        var data = {      questions: [{              question: "Which interests you most?",              options: [ "Medicine" , "Drama" ]          }, {              question: "Which interests you most?",              options: [ "Biology" , "Music" ]          }, {              question: "Which interests you most?",              options: [ "Chemistry" , "Sculpting" ]          }, {              question: "Which interests you most?",              options: [ "Psychology" , "Design" ]          }, {              question: "Which interests you most",              options: [ "Animals" , "Art" ]          }, {              question: "Which interests you most",              options: [ "Maths" , "Outdoors" ]          }, {              question: "Which interests you most?",              options: [ "Engineering" , "English" ]          }, {              question: "Which interests you most?",              options: [ "Computing" , "Ancient history" ]          }, {              question: "Which interests you most?",              options: [ "Physics ", "Dance" ]          }, {              question: "Which interests you most?",              options: [ "Geography" , "Fashion" ]          }, {              question: "Which interests you most?",              options: [ "History" , "Dentistry" ]          }, {              question: "Which interests you most?",              options: [ "Debating" , "Photography" ]          }, {              question: "Which interests you most?",              options: [ "Creative Writing" , "Accounting" ]          }, {              question: "Which interests you most?",              options: [ "Archaeology " , "Hospitality" ]          }, {              question: "Which interests you most?",              options: [ "Construction " , "Teaching" ]          }, {              question: "Which interests you most?",              options: [ "Graphics" , "Philosophy" ]          }, {              question: "Which interests you most?",              options: [ "Business" , "Drawing" ]          }, {              question: "Which interests you most?",              options: [ "Nutrition" , "Politics" ]          }, {              question: "Which interests you most?",              options: [ "Sports" , "IT" ]          }, {              question: "Which interests you most?",              options: [ "Economics" , "Languages" ]          },],      geeks: [          {              name: "Linus Torvalds",              info: "Linus Benedict Torvalds is a Finnish American software engineer, who was the principal force behind the development of the Linux kernel that became the most popular kernel for operating systems."          }, {              name: "Dennis Ritchie",              info: "Dennis MacAlistair Ritchie was an American computer scientist. He created the C programming language and, with long-time colleague Ken Thompson, the Unix operating system."          }, {              name: "Bill Gates",              info: "William Henry 'Bill' Gates III is an American business magnate, philanthropist, investor, computer programmer, and inventor."          }, {              name: "Steve Jobs",              info: "Steven Paul 'Steve' Jobs was an American entrepreneur, marketer, and inventor, who was the cofounder, chairman, and CEO of Apple Inc."          }, {              name: "Steve Wozniak",              info: "Stephen Gary 'Steve' Wozniak, known as 'Woz', is an American inventor, electronics engineer, and computer programmer who co-founded Apple Computer with Steve Jobs and Ronald Wayne."          }, {              name: "Mark Zuckerberg",              info: "Mark Elliot Zuckerberg is an American computer programmer and Internet entrepreneur. He is best known as one of five co-founders of the social networking website Facebook. Zuckerberg is the chairman and chief executive of Facebook, Inc."          }, {              name: "Tim Berners-Lee",              info: "Sir Timothy John 'Tim' Berners-Lee, also known as TimBL, is an English computer scientist, best known as the inventor of the World Wide Web."          }]  };    var qIndex = 0,      index = 0,      aString = "",      maxQ = 20,      q = document.getElementById('ques'),      opt1 = document.getElementById('opt1'),      opt2 = document.getElementById('opt2');    function generate(){      q.innerHTML= data.questions[qIndex].question;      opt1.value= data.questions[qIndex].options[0];      opt2.value= data.questions[qIndex].options[1];  }    function optionClick(ans) {      if(qIndex%2==0){          aString+=ans;          index++;      }      qIndex++;      if(qIndex == maxQ){          redirect( "result.html?" + generateResult(aString) );      } else{          generate();      }  }    function generateResult(answers) {      if( answers=="11110" || answers=="11000" || answers=="01000" ) return 0;      else if( answers=="11111" || answers=="01010" ) return 1;      else if( answers=="10011" || answers=="00111" || answers=="00101" ) return 2;      else if( answers=="10100" || answers=="00110" || answers=="00000" ) return 3;      else if( answers=="10101" ) return 4;      else if( answers=="11101" || answers=="10010" || answers=="01111" ) return 5;      else return 6;  }    function showResult() {      var id = window.location.search.substring(1);      var Geeks = data.geeks;      var totalGeeks = Object.keys(Geeks).length - 1;      if( id > totalGeeks || id < 0 || !id ) redirect("index.html");      var name = document.getElementById("geekName");      var info = document.getElementById("geekInfo");      var img = document.getElementById("geekImage");      name.innerHTML = Geeks[id].name;      img.src = "img/"+id+".png";      img.alt =Geeks[id].name;      info.innerHTML = Geeks[id].info;  }    function redirect(url) {      window.location = url;  }  

How to validate uniqness for siblings name attribute?

Posted: 05 Jul 2016 07:15 AM PDT

I have Category model with tree structure via ancestry gem. I'd like siblings to have uniq names, for example:

Books:    Science    science (not valid)  

But

Books:    Science    Children:      Science (valid)  

How can I setup this validation?

redirect to index instead of show after create or save data

Posted: 05 Jul 2016 06:42 AM PDT

I want to go to the index view directly after entering (create/new/update) the data. Right now after entering the data the show view is displayed. I tried to change render: show into render: index, but this did not work.

This is my controller:

class ElectricityGenerationsController < ApplicationController    before_action :logged_in_user    before_action :set_electricity_generation, only: [:show, :edit, :update, :destroy]`      # GET /electricity_generations    # GET /electricity_generations.json    def index      @scenario_selection = Selection.find_by_resource("scenario").name      @selected_scenarios = Selection.find_by_resource("scenario").scenario_id      @electricity_generations = ElectricityGeneration.where(scenario_id: @selected_scenarios)      respond_to do |format|        format.html #index.html.erb        format.json {render json: @electricity_generations}      end    end      # GET /electricity_generations/1    # GET /electricity_generations/1.json    def show      @scenario_selections = Selection.find_by_resource("scenario").name      @electricity_generation = ElectricityGeneration.find(params[:id])      respond_to do |format|        format.html #show.html.erb        format.json {render json: @electricity_generations}      end    end      # GET /electricity_generations/new    def new      @scenario_selections = Selection.find_by_resource("scenario").name      @electricity_generation = ElectricityGeneration.new      respond_to do |format|        format.html #new.html.erb        format.json {render json: @electricity_generations}      end    end      # GET /electricity_generations/1/edit    def edit      @scenario_selections = Selection.find_by_resource("scenario").name      @electricity_generation = ElectricityGeneration.find(params[:id])    end      # POST /electricity_generations    # POST /electricity_generations.json    def create      @selected_scenarios = Selection.find_by_resource("scenario").scenario_id      @electricity_generation = ElectricityGeneration.new(electricity_generation_params)      @electricity_generation.id = ElectricityGeneration.last.id + 1      @electricity_generation.scenario_id = Selection.find_by_resource("scenario").scenario_id      @scenario_selections = Selection.find_by_resource("scenario").name      @electricity_generation.user_id = current_user.id      respond_to do |format|        if @electricity_generation.save          format.html { redirect_to @electricity_generation, notice: 'Electricity Generation Information was successfully created.' }          format.json { render :show, status: :created, location: @electricity_generation }        else          format.html { render :new }          format.json { render json: @electricity_generation.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /electricity_generations/1    # PATCH/PUT /electricity_generations/1.json    def update      @scenario_selections = Selection.find_by_resource("scenario").name      @electricity_generation.user_id = current_user.id      respond_to do |format|        if @electricity_generation.update(electricity_generation_params)          format.html { redirect_to @electricity_generation, notice: 'Electricity Generation was successfully updated.' }          format.json { render :show, status: :ok, location: @electricity_generation }        else          format.html { render :edit }          format.json { render json: @electricity_generation.errors, status: :unprocessable_entity }        end      end    end      # DELETE /electricity_generations/1    # DELETE /electricity_generations/1.json    def destroy      @scenario_selections = Selection.find_by_resource("scenario").name      @electricity_generation.destroy      respond_to do |format|        format.html { redirect_to electricity_generations_url, notice: 'Electricity generation was successfully destroyed.' }        format.json { head :no_content }      end    end        private      # Use callbacks to share common setup or constraints between actions.      def set_electricity_generation        @electricity_generation = ElectricityGeneration.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def electricity_generation_params        params.require(:electricity_generation).permit(:user_id, :annual_solar_irradiation, :asi_max, :asi_min, :scenario_id)      end  end  

Curl in vagrant to reference itself

Posted: 05 Jul 2016 07:35 AM PDT

I currently have a project running on a Ubuntu virtual machine on my computer. I am using Vagrant and Virtual Box to set up this environment and have the Puma server up and running with the command:

bundle exec puma  

Which provided the following output:

Puma starting in single mode...  * Version 3.4.0 (ruby 2.3.0-p0), codename: Owl Bowl Brawl  * Min threads: 0, max threads: 16  * Environment: development  D [2016-07-04 11:26:23 $2728] DEBUG | : Register a receiver for (reschedule) queue  D [2016-07-04 11:26:25 $2728] DEBUG | : Register a receiver for (trial) queue  D [2016-07-04 11:26:25 $2728] DEBUG | : Register a receiver for (free) queue  D [2016-07-04 11:26:25 $2728] DEBUG | : Register a receiver for (renew) queue  D [2016-07-04 11:26:25 $2728] DEBUG | : Register a receiver for (renew_charge_response) queue  D [2016-07-04 11:26:25 $2728] DEBUG | : Register a receiver for (merchant_notification) queue  D [2016-07-04 11:26:25 $2728] DEBUG | : Register a receiver for (renew_charge) queue  D [2016-07-04 11:26:25 $2728] DEBUG | : Register a receiver for (partial_renew_charge) queue  * Listening on tcp://0.0.0.0:9292  Use Ctrl-C to stop  

I wish to now be able to make calls to this via curl commands. At present I am able to curl to the live API which leads me to believe that my curl command is correct however when i do the same to my test environment, contained within my virtual machine I get an error referring to "Basic Auth required". From this I am assuming that I am hitting the API correctly as the error returned is one contained within the API code. My problem is Basic Authentication as I have created a user and password in my environment. I have base64 encoded this and fed the resulting string into my curl statement like below:

curl -L http://127.0.0.1:9292/v2.2/ -H "Authorization: Basic cGF5bWVudHM6cGF5bWVudHM="  

For some reason it is not being accepted. Can anyway provide me with some indication as to how I could go about diagnosing the problem. Thanks in advance.

Deploy a rails app to a private server using AZK

Posted: 05 Jul 2016 06:03 AM PDT

I'm trying this time to deploy my rails app on a Scaleway VC1 server (Ubuntu 14.04LTS / 2 x86 64bits Core / 2Go RAM).

I'm using AZK, and in particular the azukiapp/deploy docker image (version 0.0.7).

I unfortunatly encounter a problem during deployment, as this log suggest :

| > azk deploy -vvv    PLAY [all] *********************************************************************    TASK [setup] *******************************************************************    Enter passphrase for key '/root/.ssh/xxx':   ok: [default]    TASK [configure : Create user and add him to docker group] *********************  changed: [default]    TASK [configure : Accept azk terms of use] *************************************  changed: [default]    TASK [configure : Ensure /etc/resolver path exists] ****************************  ok: [default]    TASK [configure : Ensure required directories exists] **************************  changed: [default] => (item=/home/git/d1fdb3d.git)  changed: [default] => (item=/home/git/d1fdb3d)  changed: [default] => (item=/home/git/.ssh)  changed: [default] => (item=/home/git/bin)    TASK [configure : Ensure authorized_keys exists] *******************************  changed: [default]    TASK [configure : Create git repository] ***************************************  changed: [default]    TASK [configure : Ensure repository permissions] *******************************  changed: [default]    TASK [configure : Apply templates] *********************************************  changed: [default] => (item={u'dest': u'/home/git/bin/azk-start', u'src': u'azk-start.j2', u'mode': u'0755', u'owner': u'git'})  changed: [default] => (item={u'dest': u'/home/git/bin/git-checkout', u'src': u'git-checkout.j2', u'mode': u'0755', u'owner': u'git'})  changed: [default] => (item={u'dest': u'/home/git/bin/rollback', u'src': u'rollback.j2', u'mode': u'0755', u'owner': u'git'})  changed: [default] => (item={u'dest': u'/home/git/bin/versions', u'src': u'versions.j2', u'mode': u'0755', u'owner': u'git'})  changed: [default] => (item={u'dest': u'/home/git/d1fdb3d.git/hooks/post-receive', u'src': u'post-receive.j2', u'mode': u'0755', u'owner': u'git'})  changed: [default] => (item={u'dest': u'/etc/dbus-1/system.d/Upstart.conf', u'src': u'Upstart.conf.j2', u'mode': u'0644', u'owner': u'root'})  changed: [default] => (item={u'dest': u'/etc/init/azk-agent.conf', u'src': u'azk-agent.conf.j2', u'mode': u'0644', u'owner': u'root'})  changed: [default] => (item={u'dest': u'/etc/init/azk-all.conf', u'src': u'azk-all.conf.j2', u'mode': u'0644', u'owner': u'root'})  changed: [default] => (item={u'dest': u'/etc/init/azk.conf', u'src': u'azk.conf.j2', u'mode': u'0644', u'owner': u'root'})  failed: [default] (item={u'dest': u'/etc/resolver/dev.azk.io', u'src': u'resolver.j2', u'mode': u'0644', u'owner': u'root'}) => {"failed": true, "item": {"dest": "/etc/resolver/dev.azk.io", "mode": "0644", "owner": "root", "src": "resolver.j2"}, "msg": "AnsibleUndefinedVariable: 'ansible_docker0' is undefined"}    NO MORE HOSTS LEFT *************************************************************      to retry, use: --limit @playbooks/configure.retry    PLAY RECAP *********************************************************************  default                    : ok=8    changed=6    unreachable=0    failed=1     

Seems to be related to Ansible. Should I install something on the remote server prior deployment ?

Here is the deploy part of my Azkfile.js if it helps :

deploy: {          image: {docker: 'azukiapp/deploy:0.0.7'},          mounts: {              '/azk/deploy/src': path('.'),              '/azk/deploy/.ssh': path('#{env.HOME}/.ssh'), // Required to connect with the remote server              '/azk/deploy/.config': persistent('deploy-config')          },          scalable: {default: 0, limit: 0},          envs: {              GIT_REF: 'azk',              REMOTE_HOST: 'xxx.xxx.xxx.xxx',              SSH_PRIVATE_KEY_FILE: 'xx'          }      }  

Thanks your time/help.

How to generate and share SP SAML 2.0 metadata in rails

Posted: 05 Jul 2016 05:59 AM PDT

I have this one which is I guess is following SAML 1.1, I wanted to know how can I generate a new SP metadata using SAML 2.0 in Rails and share with other users, which will help other team in configuring SAML at IDp(Identity Provider end)?

def get_settings      settings = Onelogin::Saml::Settings.new          settings.issuer                          = "https://example.com/test"          settings.idp_sso_target_url                ="https://testexample.com"        settings.idp_cert_fingerprint             ="########"      settings.relying_party_identifier         = "knsdfnsdf"          settings.assertion_consumer_service_url   = "https://www.example.com/consume?http_referer=https://testexample.com"      settings.idp_confirmation_method          = "urn:oasis:names:tc:SAML:1.0:cm:bearer"      settings.asserting_party_id               = "23424dfsdf"                  settings.referer_url = "https://textexample.com"       settings.groups                           = ["USER"]      settings    end  

Is there any way by which I can generate it and share it with the IDp to configure SAML process.

How to properly get value from a check_box?

Posted: 05 Jul 2016 07:05 AM PDT

I am trying to get a value from a checked check_box that is not a column in the model. The variable is always nil, however. What exactly am I doing wrong?

_form.html.erb

<%= survey_form.check_box :end_time_check, :class => 'checkbox show-toggle' , :data => { :target => "

No comments:

Post a Comment