Wednesday, September 14, 2016

jQuery/CSS bar percentage not working in rails app | Fixed issues

jQuery/CSS bar percentage not working in rails app | Fixed issues


jQuery/CSS bar percentage not working in rails app

Posted: 14 Sep 2016 07:38 AM PDT

I've forked a bar percentage, and it works well in codepen. When I paste the code snippet html/css/js into my rails app, it doesn't work. There's no animation, no data-percentage display.

bar percentage not working in rails app Now, What should I do?


Bar Percentage code snippets in codepen:

$('.bar-percentage[data-percentage]').each(function() {    var progress = $(this);    var percentage = Math.ceil($(this).attr('data-percentage'));    $({      countNum: 0    }).animate({      countNum: percentage    }, {      duration: 2000,      easing: 'linear',      step: function() {        // What todo on every count        var pct = Math.floor(this.countNum) + '%';        progress.text(pct) && progress.siblings().children().css('width', pct);      }    });  });
#container {    text-align: center;    margin: 20px;  }  h2 {    color: #CCC;  }  a {    text-decoration: none;    color: #EC5C93;  }  .bar-main-container {    margin: 10px auto;    width: 300px;    height: 50px;    -webkit-border-radius: 4px;    -moz-border-radius: 4px;    border-radius: 4px;    font-family: sans-serif;    font-weight: normal;    font-size: 0.8em;    color: #FFF;  }  .wrap {    padding: 8px;  }  .bar-percentage {    float: left;    background: rgba(0, 0, 0, 0.13);    -webkit-border-radius: 4px;    -moz-border-radius: 4px;    border-radius: 4px;    padding: 9px 0px;    width: 18%;    height: 16px;  }  .bar-container {    float: right;    -webkit-border-radius: 10px;    -moz-border-radius: 10px;    border-radius: 10px;    height: 10px;    background: rgba(0, 0, 0, 0.13);    width: 78%;    margin: 12px 0px;    overflow: hidden;  }  .bar {    float: left;    background: #FFF;    height: 100%;    -webkit-border-radius: 10px 0px 0px 10px;    -moz-border-radius: 10px 0px 0px 10px;    border-radius: 10px 0px 0px 10px;    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";    filter: alpha(opacity=100);    -moz-opacity: 1;    -khtml-opacity: 1;    opacity: 1;  }  /* COLORS */    .azure {    background: #38B1CC;  }  .emerald {    background: #2CB299;  }  .violet {    background: #8E5D9F;  }  .yellow {    background: #EFC32F;  }  .red {    background: #E44C41;  }
<head>    <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>  </head>    <div id="container">    <h2><strong>Bar percentage</strong> inspired by this <a href=      "http://dribbble.com/shots/1090476-Percentage-Bar">dribbble shot</a></h2>      <div id="bar-1" class="bar-main-container azure">      <div class="wrap">        <div class="bar-percentage" data-percentage="46"></div>        <div class="bar-container">          <div class="bar"></div>        </div>      </div>    </div>      <div id="bar-2" class="bar-main-container emerald">      <div class="wrap">        <div class="bar-percentage" data-percentage="94"></div>        <div class="bar-container">          <div class="bar"></div>        </div>      </div>    </div>      <div id="bar-3" class="bar-main-container violet">      <div class="wrap">        <div class="bar-percentage" data-percentage="47"></div>        <div class="bar-container">          <div class="bar"></div>        </div>      </div>    </div>      <div id="bar-4" class="bar-main-container yellow">      <div class="wrap">        <div class="bar-percentage" data-percentage="85"></div>        <div class="bar-container">          <div class="bar"></div>        </div>      </div>    </div>      <div id="bar-5" class="bar-main-container red">      <div class="wrap">        <div class="bar-percentage" data-percentage="33"></div>        <div class="bar-container">          <div class="bar"></div>        </div>      </div>    </div>    </div>

Redmine + apache+ Passenger: Passenger still runs as nobody

Posted: 14 Sep 2016 07:35 AM PDT

I'm installing a new version of redmine under debiane8, i followed the steps here: http://www.redmine.org/projects/redmine/wiki/HowTo_Install_Redmine_on_Debian_8_with_Apache2-Passenger

i had some problems with passenger so i install it using: "gem install passenger" and "passenger-install-apache2-module".

I added: PassengerDefaultUser www-data on the passenger confing file and on the appache config file as well. to avoid permission problems

The problem is that passenger is still running as nobody

result of top | grep "passenger" gives 3 process named PassengerAgent, 2 of them runs as root and one runs as nobody, what should i do to have the effect of the configuration i added. I have : Redmine version 3.3.0.stable Ruby version 2.1.5-p273 (2014-11-13) Rails version 4.2.6

Can Active fedora connect to two solr instances at the same time?

Posted: 14 Sep 2016 07:35 AM PDT

Can Active fedora connect to two solr instances ? If possible, how does the solr.yml look like?

How do you add headers to a Net::Http::Post request in Ruby?

Posted: 14 Sep 2016 07:30 AM PDT

I'm using Rails 4.2.7. How do I add headers to a Net::HTTP::Post request? I tried

    params = {"SubmitButton" => "View"}      …        headers = {"Referer" => url}        req = Net::HTTP::Post.new(uri, params.to_query, headers)  

However when I run this code I get the error

Error during processing: wrong number of arguments (given 3, expected 1..2)  /Users/davea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http/request.rb:14:in `initialize'  /Users/davea/Documents/workspace/myproject/app/services/marathon_guide_race_finder_service.rb:97:in `new'  /Users/davea/Documents/workspace/myproject/app/services/marathon_guide_race_finder_service.rb:97:in `block in process_race_link'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/node_set.rb:187:in `block in each'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/node_set.rb:186:in `upto'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/node_set.rb:186:in `each'  

Note I want to add the headers to the object before it is sent.

What gem produces this output '\_ Called from:'

Posted: 14 Sep 2016 07:36 AM PDT

I started working on a existing rails project and in the rails server output there are these extra lines:

User Load (10.3ms)  SELECT "users".* FROM "users" WHERE "users"."email" = 'miles@milestshirts.com' LIMIT 1  \_ Called from: app/controllers/application_controller.rb:10:in `block in <class:ApplicationController>'  

Basically for each SQL query in my rails app it adds a line who called it. I can't seem to find it in the Gemfile as it has over a 150 gems.

And it is not https://github.com/ruckus/active-record-query-trace

Rails MaterializeCSS Passing User.id to Modal

Posted: 14 Sep 2016 07:21 AM PDT

As the title suggests, I've want to use MaterializeCSS Modal to show User data. The problem currently is that though each card has a trigger, All triggers show the same Modal. I'm assuming it's because no object data is being passed through. What is the best method for me to solve this problem? Thank you!

           <%@member.each do |x|%>             <div class="member-card z-depth-2">               <a href="/users/<%=x.id%>">               <img src="<%=x.avatar%>"/>               </a>               <div class="member-info">                 <strong><%=x.first_name.capitalize!%> <%=x.last_name.capitalize!%></strong>                 <button data-target="modal1" class="btn modal-trigger" id="<%=x.id%>" >About Me</button>                 <div id="modal1" class="modal">                   <div class="modal-content">                     <img src="<%=x.avatar%>" alt="" height="300px" width="350px"/>                     <h4><%=x.first_name.capitalize!%></h4>                   </div>                   <div class="modal-footer">                     <a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat">Agree</a>                   </div>                 </div>               </div>             </div>             <%end%>  

$(document).ready(function(){

// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); });

NVDA 508 Compliance - ROR

Posted: 14 Sep 2016 07:18 AM PDT

I have an application built on Ruby on Rails. Anyone got any idea on how to make a web application NVDA 508 compliant. I have read different articles, but not getting exact information on steps needed to do this. Anyone done this before?

Thanks in advance.

Startup project with rails + polymer

Posted: 14 Sep 2016 07:15 AM PDT

I am using rails till now for fronted. but now i have to use polymer + rails. I already bundle emcee. but don't know how to use in application. Is there any start guide that help me to start with polymer + rails ( set-up + start-up guide )

Scenario: I have a polymer project all I just need is that how can I use that polymer project with rails and call the polymer page from rails as root.

So is there any guide which help me to startup with project

Thanks in advance.

Scope active record based on association count

Posted: 14 Sep 2016 07:32 AM PDT

Two models, Users and Portfolios. Each user can have multiple portfolios and each portfolio can either be full or empty (boolean).

How do I scope users based on the number of full and empty portfolios they have?

I need it as a relation so I can't use select otherwise this would work (example for all users with more than one full portfolio and only one empty):

User.select { |user| user.portfolios(full: true).count > 1 &&                       user.portfolios(full: false).count == 1 }  

Link to corresponding path in other locale (rails)

Posted: 14 Sep 2016 07:12 AM PDT

I have a multi-lingual application in Ruby on Rails 4. For that I use the following domains:

  • Swedish: exempel.se
  • English: example.com
  • French: fr.example.com
  • Spanish: es.example.com

I want to be able to link to the corresponding path in another corresponding locale. For example if I am at www.exempel.se/denna-bloggpost I want to be able to easily link to (English/Spanish/French) to e.g. www.example.com/this-here-blog-post and es.example.com/este-posto-de-bloggo (sorry, can't speak Spanish :)).

I understand this is done with link_to 'Spanish', locale => :es but this gives me the url www.exempel.se/denna-bloggpost?locale=es which is not what I want. I expect to access es.example.com/esto-posto-de-bloggo

It seems like default_url_options has something to do with this but I can't make it work.

How do I solve this?

undefined method `primary_key' for ProtocolProcess:Module

Posted: 14 Sep 2016 06:59 AM PDT

I created a model InsertInbox, but I did not create a controller for the model:

rails generate model Process_inbox protocol_id:integer sector_id:integer

class ProcessInbox < ApplicationRecord    end  

and I created a module in lib folder:

module ProtocolProcess    def insert_inbox(protocol_id, sector_id)       ProcessInbox.where(protocol_id: protocol_id,sector_id: sector_id).first_or_create    end  end  

and call the insert_inbox method in my controller:

class ProtocolsController < ApplicationController    require 'protocol_process'      def create        @protocol = Protocol.new(protocol_params)         if @protocol.save            insert_inbox(@protocol.id,current_user.sector)        else          end    end  end  

but the error is displayed:

**NoMethodError in ProtocolsController#create  undefined method `primary_key' for ProtocolProcess:Module**  

when I run the code in the rails console it works

Rails: Why is only one email sent to the last member of a loop?

Posted: 14 Sep 2016 06:45 AM PDT

I am very much a rails novice!

I am trying to write a method for a kind of on-line committee meeting. There are a fixed number(9) of users. When a user proposes a topic for discussion and/or voting the submit button needs to send an email to all members.

in app/mailers/user_mailer.rb I have:-

class UserMailer < ApplicationMailer      def new_topic_alert(topic)      @users = User.all      @users.each do |user|        mail to: user.email, subject: "New topic alert"      end    end  end  

as part of app/controllers/topics_controller.rb I have:-

def send_alert    @topic = Topic.new(topic_params)    UserMailer.new_topic_alert(@topic).deliver_now  end  

and:-

def create    @topic = Topic.new(topic_params)    if @topic.save      send_alert      flash[:info] = "New Topic alert emails sent."      redirect_to root_url    else      render 'new'    end  end  

Please, why does the loop in user_mailer only send an email to the final person of the list. By incorporating "byebug" I have shown that it goes through all the user emails.

Unable to authenticate loggedin user based on session ROR - Refinery CMS

Posted: 14 Sep 2016 06:21 AM PDT

I have installed refinery cms and need to add custom controller, currently I have added all my controllers and they are working fine as well.

Basically, its admin controller that is other than refinery controllers whom I wants to authenticate if user is not logged in.

so, if no user is logged into the site, it will redirect it to refinery/login page.

I have admin controller whose code is like:

require 'refinery/core/nil_user'    class AdminController < ApplicationController # Refinery::Admin::CoreController    include RefineryAuthenticationPatch      include ::Refinery::ApplicationController    helper Refinery::Core::Engine.helpers      include Refinery::Admin::BaseController    include Refinery::Authentication::Devise  end  

My gem file:

gem 'refinerycms'  gem 'refinerycms-authentication-devise', '~> 1.0.4'  gem 'refinerycms-wymeditor', '~> 1.0', '>= 1.0.6'  

Some page code:

<%= form_for([:admin, @current_object]) do |f| %>      <div class='field'>        <%= f.label :title %>        <%= f.text_field :title, :class => 'larger widest' %>      </div>  <% end %>  

And my link is something like: http://localhost:3000/admin/teachers/new. These links are of in great number so I wants to authenticate all of them. So, if user try to access these pages by putting URL in browser, so it will redirect user to login page.

Simply, what I need to do is if some one directly access http://localhost:3000/admin/teachers/new page, he should redirected to refinery/login page.

For all other controllers or pages the behavior is working fine but I want to fix it for these custom pages now.

I have tried loads of codes and things regarding device or refinery authentications but all in vain.

Here is my reference question on google group as well:

https://groups.google.com/forum/#!topic/refinery-cms/yQ_OWIKxLdY

Net::OpenTimeout (execution expired) exception on Sidekiq

Posted: 14 Sep 2016 06:19 AM PDT

I'm using sidekiq to to queue the emails my Rails application will send. Sending emails works in development, but in production sidekiq will get a network timeout error. What's going on?

Here's my config in production.rb

config.action_mailer.delivery_method = :smtp  config.action_mailer.smtp_settings = {    address:              'smtp.gmail.com',    port:                 578,    domain:               'localhost:3000',    user_name:            ENV["GMAIL_USERNAME"],    password:             ENV["GMAIL_PASSWORD"],    authentication:       :plain,    enable_starttls_auto: true  }  config.active_job.queue_adapter = :sidekiq  

I have tried the following:

  1. Disabling IPv6 and setting IPv4 as the preferred
  2. Using a non-standard port (2525) instead of 587
  3. Tried connecting via telnet smtp.gmail.com 587. I get the following error: telnet: Unable to connect to remote host: Network is unreachable. It might be worth noting that I'm operating behind a proxy - should there be an additional setup in this case?
  4. sudo ufw allow 587

I'm on an Ubuntu 14.04 server and have set up my app using unicorn and nginx.

I've been at this for days. :( Any help would be greatly appreciated!

Rails 4 : how to runTCPserver connection in controller action

Posted: 14 Sep 2016 06:03 AM PDT

I am using ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux] and Rails 4.2.4 on cloud9 IDE

I am doing TCP socket programming using below files in cmd. it's working fine . now i want to run these code in controller action and view result in my application html page.is it possible ?

how should i write Client.rb

require 'socket'    hostname = 'localhost'  port = 8082  s = TCPSocket.open(hostname,port)  s.write ("hello server i'm your client")  s.close  

Server.rb

require 'socket'

server = TCPServer.new 8082  loop do    Thread.start(server.accept) do |client|      response = client.gets      puts response      client.close    end  end  

NOTE: I am using colud9 IDE. which port number should i give if it is possbile to do in controller's action.my application running on port:8080

How to use React Router on top of Rails router (not using react-rails gem)?

Posted: 14 Sep 2016 05:59 AM PDT

Now i am making React app on top off Ruby on Rails app (with out react-rails gem) by using browserify-rails to compile js files.

So i tried to us react-router to config router of the app

This is my main.js

import React from 'react';  import ReactDOM  from 'react-dom';  import { Router, Route } from 'react-router';  import { browserHistory } from 'react-router';    /*Import Component*/    import DashBoard from './components/dashboard';  import Group from './components/dashboard';    /*   *   * Routes   *   * */    var routes = (      <Router history={browserHistory}>          <Route path="/" component={DashBoard}/>          <Route path="/group" component={Group}/>      </Router>  );    ReactDOM.render(routes , document.querySelector('#main'));  

But when i go to

http://my.app.dev/group  

I got

No route matches [GET] "/group" (From Rails)  

So how can i fix this and make React Router on top off Rails router?

Thanks!

Dealing with incoming data with aliases

Posted: 14 Sep 2016 06:09 AM PDT

Bit of a philosophical question this one:

We deal with lots of data that comes in via different channels. We're parsing that data to try to make sense of it.

e.g.

class Product  attr_accessible :name, :description, :price  has_one :company  end    class Company  attr_accessible :name, :domain, :phone, :email  validates_uniqueness_of :name, :domain    end  

When the data comes in the company names can vary a bit.

e.g.

"Acme Limited"  "Acme Ltd"  "Acme Ltd (Birmingham)"  "Acme Ltd (London)"  

These are all fundamentally the same company and we'd like to store them as such and automatically assign them (once we've identified an alias).

The variations are down to the way that third parties store the data in their APIs, or on sites which we have no control over.

What's a good way of identifying these aliases and then converting them to the appropriate company as they arrive?

I've thought about adding another class as an association to Company that deals with aliases. Alternatively, adding a jsonb column to the table where we can keep an array of aliases, so that if any match we can bring them in.

Just seems like there should be a good solution to this that I'm not finding.

Anyone run into this type of issue and come up with something elegant and beautiful?

Elasticsearch issue: Cannot connect AWS elasticsearch service

Posted: 14 Sep 2016 05:24 AM PDT

I have a issue about configure elasticsearch to connect AWS elasticsearch service to run project in production. My Gemfile:

    gem 'searchkick'      gem 'faraday_middleware-aws-signers-v4'      gem 'aws-sdk', '~> 2'      gem "elasticsearch", ">= 1.0.15"  

Reference: https://github.com/ankane/searchkick

My config/initializers/elasticsearch.rb file:

    require "faraday_middleware/aws_signers_v4"      ENV["ELASTICSEARCH_URL"] = "https://search-eaterybot-u3yjm6cdn3ogkmv3bcdl5j7poy.ap-southeast-1.es.amazonaws.com/"           Searchkick.client = Elasticsearch::Client.new(         url: ENV["ELASTICSEARCH_URL"],          transport_options: {request: {timeout: 10}}         ) do |f|         f.request :aws_signers_v4, {credentials: Aws::Credentials.new(Rails.application.secrets.aws_access_key_id, Rails.application.secrets.aws_secret_access_key),         service_name: "es",         region: "ap-southeast-1"       }     end  

When I run "rake searchkick:reindex:all", it show error:

Elasticsearch::Transport::Transport::Errors::Forbidden: [403] {"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been\n'GET\n/_aliases\n\naccept-encoding:gzip;q=1.0,deflate;q=0.6,identity;q=0.3\nhost:search-eaterybot-u3yjm6cdn3ogkmv3bcdl5j7poy.ap-southeast-1.es.amazonaws.com\nx-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\nx-amz-date:20160914T095023Z\n\naccept-encoding;host;x-amz-content-sha256;x-amz-date\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'\n\nThe String-to-Sign should have been\n'AWS4-HMAC-SHA256\n20160914T095023Z\n20160914/ap-southeast-1/es/aws4_request\n47bc69b4440a13aeac990b8c6c49934f1dcc4693bbbda577bfdeb02e685c507b'\n"}"

Anyone can help me! Thanks!

NameError in Admin::Recommandations#index

Posted: 14 Sep 2016 05:23 AM PDT

I have multiple ressources on my ActiveAdin interface, one of them returns me an error when i go on the Index view "/admin/recommandations" with the following message :

NameError in Admin::Recommandations#index   Showing /home/charles/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/bundler/gems/activeadmin-0a5a15b88bff/app/views/active_admin/resource/index.html.arb where line #2 raised:   uninitialized constant Recommandation::Writer  

The recommendation functionality is simple : one user can rate an other user by making a recommendation. In my Recommandation model I have one user (the one who is rated) and a Writer (the one who write the recommendation).

Recommandation model :

class Recommandation < ActiveRecord::Base    before_validation:check_models      belongs_to :user    validates :user_id, presence: true    validates_associated :user      # Il s'agit de l'utilisateur qui inscrit la recommandation    has_one :writer, :foreign_key => "writer_id"     validates :writer_id, presence: true    validates_associated :writer      validates :modele, presence: true      ##    # @return L'origine liƩe    def writer      if self.writer_id != nil        User.find(self.writer_id)      end    end  

I can access each of my Recommandation ressources with "/admin/recommandations/1" and there is a writer which is a user so I don't understand where the problem is.

How to iterate over an array with hash [duplicate]

Posted: 14 Sep 2016 05:26 AM PDT

How to iterate over an array with hash that has the position included? Could I remove it? I've never come across this before.

var data = [   {     id: 1,     foo: "hello",     ...,   },   {     id: 2,     foo: "world",     ...,   }  ]  

When I POST this data to my controller, in my console I see the data params also includes the position (0, 1, 2, etc) so I cant iterate over it properly. The full look would be:

React:

...    $.ajax({    url: '/the-url',    type: 'POST',    data: {'line_items': data, // this would have been this.state.data            ...          },    success: function (data, xhr) {        console.log("success")      }.bind(this),    error: function (data) {        console.log("error")    }  });    ...  

Controller:

...    line_items = params[:line_items]  line_items.map do |l| l.id end # error    ...  

Console:

0  {"id"=>"1", "foo"=>"hello"},  1  {"id"=>"2", "foo"=>"world"},  

Also Rails 5 says map is depreciated. So what to use?

Local variable in Ruby on Rails is undefined

Posted: 14 Sep 2016 07:01 AM PDT

I am currently following a recipe box tutorial on youtube. When I open the rails console and say

@recipe = current_user.recipes.build  

I got following error:

NameError: undefined local variable or method current_user' for main:Object from (irb):3 from /Users/matthiascordes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands/console.rb:65:instart' from /Users/matthiascordes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands/console_helper.rb:9:in start' from /Users/matthiascordes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:78:inconsole' from /Users/matthiascordes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in run_command!' from /Users/matthiascordes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in' from bin/rails:9:in require' from bin/rails:9:in'

Does anybody has an idea what is wrong and how I can solve this problem? I am using the devise gem for my user model.

Find closing tag missing that disables jQuery plug in | Rails 5 |?

Posted: 14 Sep 2016 04:54 AM PDT

I have a jQuery Raty plugin that's not working on my WebApp.

The jQuery plugin worked when I added a partial with a missing closing tag:

Partial:

<script    src="https://checkout.stripe.com/checkout.js" class="stripe-button"    data-key="<%= Rails.configuration.stripe[:pk_test_Ht7SG3skQy8jHhCMnW5ZJeHf] %>"    data-image="<%= @product.image_url %>"    data-name="<%= @product.name %>"    data-description="<%= @product.description %>"    data-amount="<%= (@product.price*100).to_i %>"  </script>  

Closing tag missing in:

 data-amount="<%= (@product.price*100).to_i %>"   

which should be

data-amount="<%= (@product.price*100).to_i %>">  

When I correct the closing tag on that Partial, the jQuery Raty Plugin is disabled again. I am going nuts trying to find the part of the code that's disabling my jQuery.

Any ideas where to exactly look for it?

Here's the commit with the code related to the jQuery plugin:

https://github.com/jen-v/nameofapp/commit/07e9296981dbbe09a12b0214517ba84024c2d606

RAILS - issue with the recipient format in mailboxer / Array / String?

Posted: 14 Sep 2016 06:47 AM PDT

I am struggling with a form for mailboxer gem ( to send some messages within the app)

I pass the recipient username though this link :

<%= link_to "", new_conversation_path(:recipients => search.pseudo), class: "fa fa-envelope fa-1x" %>  

That part is working fine, i got the NAME of the recipients in the URL Parameters.

URL /conversations/new?recipients=NAME

then the form , the second part after the Else , is working too , but it pass 2 parameters Pseudo & Id, I dont really know how to do same for the first part. The first part is the one I need when i pass the parameters though the link.

<% if params[:recipients].present? %>        <div class="form-group">           <%= f.label :recipients %>           <%= text_field_tag(:recipients, "#{@user.pseudo}") %>        </div>        <%else%>        <div class="form-group">            <%= f.label :recipients %>            <%= f.select(:recipients, User.all.collect {|p| [ p.pseudo, p.id ] }, {}, { multiple: true , class: "chosen-select form-control" })%>         </div>  <%end%>  

and here is the controller :

def create      recipients = User.where(id: conversation_params[:recipients])      conversation = current_user.send_message(recipients, conversation_params[:body], conversation_params[:subject]).conversation      flash[:success] = "Your message was successfully sent!"      redirect_to conversation_path(conversation)   end    def new  @user = User.find_by(pseudo: params[:recipients])  end  

Ideas on why when deployed on Heroku, value shows date whereas locally it is datetime?

Posted: 14 Sep 2016 04:39 AM PDT

I have a model english_grade which has a column grade_datetime which is a datetime selected by the user in a form.

  <div class="field">      <%= f.label :grade_datetime %>      <%= f.datetime_select :grade_datetime %>    </div>  

When I display the value on a view. Locally they appear as datetime (e.g. which is 2016-09-13 23:25:00 +0100), whereas in Heroku they appear as date (e.g. 2016-09-14). I'm not sure what would be the most useful information to include but I have tried to set my timezone to London (my location).

I'm not sure from a high level perspective where I should be looking to solve this problem and can't find anything on Google. Will edit question appropriately based on what additional information anyone thinks would be relevant.

Any ideas of what could be causing the issue or requests for extra info would be appreciated! Thanks a lot!!!!

Rails 4 Error: Retrieving Params out of URL

Posted: 14 Sep 2016 05:33 AM PDT

I am fairly new to rails and I am struggling getting the id param out of this url:

http://localhost:3000/subscriberjobs/new?job_id=13  

My goal is to update certain values of a Job (Model) after it got created AND got paid via Stripe. Take a look at the Userflow for more details.

Userflow:

  1. Form to setup their Job (below / Job Model) =>

    redirect_to "/subscriberjobs/new?job_id=#{@job.id}"  

(http://localhost:3000/jobs/new)

  1. (Job Controller) => Getting Payment via Stripe => http://localhost:3000/subscriberjobs/new?job_id=13
  2. (Subscriberjobs Controller) => Update the values of this Job. (http://localhost:3000/subscriberjobs/1) #needs to get changed

Problem: No matter which Job(id) got created, it always updates Job.find(1).

I guess it is because when it tries to receive :job_id/:id it already got redirected to /subscriberjobs/1 due to the succeeded payment via Stripe. That's why it extracts always :id => "1".

The Form:

= simple_form_for @job do |f|    = f.input :company, required: true    = f.input :title, required: true    = f.input :job_filename    = f.input :location, required: true    = f.input :sort    = f.input :tag_list, required: true    = f.input :content_one    = f.input :content_two    = f.input :content_three    = f.hidden_field :job_id, value: params[:id]    = f.button :submit  

Currently I am using this code to get it: (Subscriberjobs Controller)

def update    @job = Job.find_by(id: params[:id])      @job.is_active = true    @job.is_featured = false    @job.stripe_id = customer.id    @job.save      token = params[:stripeToken]      customer = Stripe::Customer.create(        card: token,        plan: 1004,        email: current_user.email        )    redirect_to root_path  end  

Any help on how to achieve what I am trying to do is much appreciated!

How do I take the input text from a html form and pass it to another form on the same page with Jquery?

Posted: 14 Sep 2016 07:36 AM PDT

I'm new to JQuery and I'm trying to add a feature into my Rails application that takes an input from a html form and runs it through some erb on the same page.

Here is what I have so far in jquery and html:

$(document).ready(function() {    $( "#search" ).on('submit', function( event ) {      event.preventDefault();      var film = $( "form input:text" ).val();    });  });
<div id="search">      <form>        Film:<br>        <input type="text" name="film"><br>        <input type="submit">      </form>    </div>    <div id="results">      <%= form_for @film do |f| %>        <% @search = Tmdb::Search.new %>        <% @search.resource('movie') %>        <% @search.query("Film to be queried)"%>        <% @results = @search.fetch %>        <% @select_list = @results.collect {|movie| [ movie['title'] + " " + movie['release_date'][0..3],           movie['title'] + "," + movie['release_date'][0..3] + "," + movie['id'].to_s + "," + movie["backdrop_path"].to_s ] } %>        <%= select_tag "film_record", options_for_select(@select_list) %>        <%= f.submit "Add film" %>      <% end %>    </div>

Where is says "Film to be queried", I want to put the film variable element set in my jquery.

I'm happy to do this a completely different way, so any suggestions are welcome!

IE Session does not work in rails

Posted: 14 Sep 2016 03:51 AM PDT

I have a website with multiple subdomains :

https://sg.epicurio.co

root domain detects the country of user and forwards to relevant sub-domain. It works in all major browsers but IE. Internet Explorer does not save any session unless I disable "Enhance Security mode" in setting. Its very troublesome for our customers to do it manually since Microsoft Edge has no direct option to do that unless switched to IE manually.

I am not sure for the problems. I am using rails 3.2.11 and tried to set the domain: 'all' in my session initializer. That worked for IE but all other browsers got the session problem so I reverted that.

Thanks in advance if Anybody can suggest a way to solve this problem

MailForm does not include a field from form when sending email

Posted: 14 Sep 2016 03:59 AM PDT

I'm trying to set up MailForm to send emails in my Rails 4 app and I actually got it working except for one thing.

For some reason it does not include the message field in emails (the form has only name, email and message fields, plus a hidden nickname field).

Here's how my Contact model looks like:

class Contact < MailForm::Base    attribute :name,     validate: true    attribute :email,    validate: /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i    attribute :message    attribute :nickname, captcha: true      append :remote_ip, :user_agent      def headers      {        subject: 'Question',        to: ENV['ACTION_MAILER_USERNAME'],        from: %("#{name}" <#{email}>)      }    end  end  

If I add validate: true to attribute :message, the validation will work incorrectly, i.e. it will say the field is empty even if it is not, so if I turn on the validation for the :message attribute, I cannot even submit the form.

In MailForm docs example there's no validation for :message field, though when I submit the form, the message that is sent to me contains only :name and :email fields, no :message.

My ContactsController.rb looks like this:

class ContactsController < ApplicationController    def new      @contact = Contact.new    end      def create      @contact = Contact.new(contact_params)      @contact.request = request      if @contact.deliver        flash.now[:notice] = I18n.t('contact.message_success')        redirect_to root_path      else        flash.now[:error] = I18n.t('contact.message_error')        render :new      end    end      private      def contact_params      params.require(:contact).permit(:name, :email, :message)    end  end  

And here's my html form:

   <%= simple_form_for @contact do |f| %>         <%= f.input :name, required: true, label: false %>         <%= f.input :email, required: true, label: false %>         <%= f.input :message, as: :text, required: true, label: false %>         <div class="hidden">             <%= f.input :nickname, hint: 'Leave this field blank!' %>         </div>         <%= f.button :submit, t('contact.action') %>     <% end %>  

So, basically, I followed the examples in MailForm docs, but still couldn't get it working correctly.

Could you help me to find out what I'm doing wrong?

Update 1

It seems like the problem is with params. Here's how params hash looks like when submitting the form:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"kOtHaOTBNvl5KpPBLB31LtQ6W0jUoohg012ZbQ5qyg0fAGW6y5mMR5FSAEcY4kyotFYihTvRSvTtbDsc8oMQ3g==", "contact"=>{"name"=>"Testing", "email"=>"whatever@test.com", "nickname"=>""}, "Message"=>"Hello everyone!", "commit"=>"Send", "locale"=>"en"}  

Custom page-break in rails

Posted: 14 Sep 2016 06:00 AM PDT

I have a ruby on rails application where in a particular view ,I have some data which is being represented in format of table . Now the user can take a print out of this page by press Ctrl+P . But some of my users asking to insert page break after particular sections in that table (some contiguous rows represent a particular section) .So that the table data will be printed section wise in separate pages.

Please help me how do it. Thanks in advance.

Error while start rails console libIlmImf.so.6: cannot open shared object file

Posted: 14 Sep 2016 04:14 AM PDT

I am trying to setup a rails project, after successfully bundle install when I try to run a rails c it gives me following error.

`require': libIlmImf.so.6: cannot open shared object file: No such file or directory - /home/user/.rvm/gems/ruby-2.3.0/gems/rmagick-2.16.0/lib/RMagick2.so (LoadError)  

I have installed "rmagick" but still gives me same error. I have also installed "openexr" as suggested in one of the SO post but didn't work for me.

Any suggestions about how to fix this?

No comments:

Post a Comment