Sunday, April 10, 2016

Ruby on rails Class being mistaken as a Constant | Fixed issues

Ruby on rails Class being mistaken as a Constant | Fixed issues


Ruby on rails Class being mistaken as a Constant

Posted: 10 Apr 2016 07:11 AM PDT

First of all, I'm experimenting with Ruby on Rails for the first time. I'm doing a simple exercise of designing a form to receive events information and save those events in Google Calendar. To save the events on Google Calendar I'm using the following gem: http://googlecalendar.rubyforge.org/

I have the following code for the view.

<h1>Welcome to Ruby On Rails Calendar</h1>    <h3>Add Event</h3>  <form action="/google_calendar/create" method="post">    <table>      <tr>        <td>Title</td><td><input type="text" /></td>      </tr>      <tr>        <td>Begin Date</td><td><input type="date" name="begindate" id="bagindate" /><input type="time" name="beginhour"  id="beginhour" /></td>      </tr>      <tr>        <td>End Date</td><td><input type="date" name="enddate" id="enddate" /><input type="time" name="endhour" id="endhour" /></td>      </tr>      <tr>        <td>Local</td><td><input type="text" name="local" id="local" /></td>      </tr>      <tr>        <td>Description</td><td><input type="textarea" rows="10" name="description" id="description" /></td>      </tr>      <tr>       <td><input type="Submit" value="Save" /></td>      </tr>    </table>  </form>    <%= @result_message %>  

And for the controller I have this code (mostly taken from the gem site I shared previously).

class GoogleCalendarController < ApplicationController      def create      send_event(params[:title],params[:begindate] + " " + params[:beginhour], params[:enddate] + " " + params[:endhour], params[:local], params[:description])        @result_message = 'Event sent successfully'      render :welcome => index    end      private def send_event(title, begin_datetime, end_datetime, local, description)      require 'googlecalendar'        google_calendar_service = GData.new      google_calendar_service.login(Rails.configuration.google_calendar_email, Rails.configuration.google_calendar_password)      event = { :title     => title,                :content   => description,                :where     => local,                :startTime => begin_datetime,                :endTime   => end_datetime}      google_calendar_service.new_event(event)    end  end  

The thing is that when I try to save an event I get the following error.

uninitialized constant GoogleCalendarController::GData  

Supposedly GData is a class defined in the googlecalendar gem, but seems to not being recognized as such.

I have gem 'googlecalendar' on my Gemfile, did bundle install and it appears when I do bundle show googlecalendar.

Does anyone know what can be causing this?

Come back on my library

Posted: 10 Apr 2016 06:51 AM PDT

I'd try to use an application using nokogiri, but after a lot of problems, i decide to uninstall it. And now I have a error to running my server. I think is because I witch to an other library with this command

bundle config build.nokogiri --use-system-libraries --with-xml2-include=/usr/local/opt/libxml2/include/libxml2

So how can I come back to my original repository ?

I use bundle install --path to remove all, if that can help you

Turn simple form checkbox into a toggle switch

Posted: 10 Apr 2016 06:32 AM PDT

I have a few checkboxes inside a simple_form_for:

<%= f.input :agree, label: "Agree with terms and conditions*" %>  

which outputs the following html:

<div class="form-group boolean optional enrollment_agree">    <div class="checkbox">      <input value="0" type="hidden" name="enrollment[agree]">      <label><input class="boolean optional" type="checkbox" value="1" name="enrollment[agree]" id="enrollment_agree"></label>    </div>  </div>  

I found a nice and simple material design toggle switch http://codepen.io/chrisota/pen/jWmqvx which works with the following html:

<input id="toggle" type="checkbox" class="hide"/>  <label for="toggle"><span class="hide">Label Title</span></label>  

How can I make it work within the rails form?

need suggestions for a more simplified devise user authentication?

Posted: 10 Apr 2016 06:29 AM PDT

I'm developing an intranet site in Rails 4 using the devise gem. What I am currently at right now is a root page that prompts the user to sign in to be able to access to the different modules page.

Now on to my question: Is there a more elegant way to authenticate the user aside from planting an if user_signed_in? on each of the pages ? I'm a little bothered if I have to use that on each of my pages beyond the login form.

How to optimise computation intensive request response on rails [duplicate]

Posted: 10 Apr 2016 06:12 AM PDT

I have an application, which does a lot of computation on few pages(requests). The web interface sends an AJAX request. The computation takes sometimes about 2-5 minutes. The problem is, by this time AJAX request times out.

We can certainly increase the timeout on the web portal, but that doesn't sound like right solution. Also, to improve performance:

  • Removed N+1/Duplicate queries
  • Implemented Caching

What else could be done here to reduce the calculation time?

Also, if it still takes longer, I was thinking of following solutions:

  • Do the computation beforehand and store it in DB. So when the actual request comes, there is no need of calculation. (Apprehensive about this approach. Since we will have to modify/Erase-and-recalculate this data, whenever there is some application logic change.)
  • Load the whole data in cache when application starts/data gets modified. But for the first time computation has to be done. Also, can't keep whole data in the cache when the application starts. So need to store it in the cache as per demand.
  • Maybe, do something like Angular promise, where promise gets fulfilled when the response comes from the server.

Do we have any alternative to do this efficiently?

Thanks.

How do I send another user a task so it appears in his tasks list?

Posted: 10 Apr 2016 06:04 AM PDT

I am working on a Task Manager app and I need to be able to send the Task I have created to another user in the system by choosing his email from the list of all registered users' emails.

After I send the task the receiver should see it in his tasks + also get all the CRUD ability for it.

Project GitHub

How to genrate multiple instances for related objects in model Rails?

Posted: 10 Apr 2016 06:32 AM PDT

I have two models one is Resident and other is Bill.

Bills--> belongs_to:residents

Residents-->has_many:bills

How can I generate bills for all residents?

like after clicking the generate now button . there must be bills created for every resident. Bills will be created using three models

leave Model--> belongs_to:residents

attributes--> start_date:datetime,end_date:datetime

rate_card Model--> belongs_to:hostel

attributes--> diet:integer,charge1:int,charge2:intcharge3:int

Account Model--> belongs_to:resident

attributes--> fine:int,leaves:difference of end-start date from leave table

bills Model--> belongs_to:resident

attributes--> From_date:date,to_date:date,payable_amount:int,is_paid:bool

bill contains a payable amount which can be generated using formula:

payable amount: 30*diet+charge1+charge2+charge3+fine*leaves

how should I create bills now for each and every resident?? I need an idea for create method thanks !!

Help me out plz.. xD

Ruby on Rails: New post not saving on the blog

Posted: 10 Apr 2016 06:07 AM PDT

I'm working on an exercise, creating a blog with ruby on rails. I have the form ready to post an article, but once I click on the submit button, I am redirected to the homepage but the article doesn't save. Here is the following code

class ArticlesController < ApplicationController    def index      @articles = Article.paginate(:page => params[:page], per_page: 5).order('created_at DESC')    end      def show      @article = Article.find(params[:id])    end      def new      @article = Article.new    end      def create      @article = Article.new(title: params.permit[:title], body: params.permit[:body])        if @article.save        redirect_to articles, :notice => "Your post has been saved"      else        render :create      end    end    end  

Here is the view create.html.haml

.container      .row          .col-xs-9-              .panel-title                  %h2 Ecrivez votre article                  = form_for @article do |f|                      = f.text_field :title                      = f.text_area :body, size: "60x12"                      = f.submit "Publier"  

Then the route.rb, I don't know if it can help

TP2::Application.routes.draw do    resources :articles, only: [:index]      get 'articles' => 'articles#index'      get 'articles/:id' => 'articles#show'      get 'articles/new'      get 'post' => 'articles#create'      post 'articles' => 'articles#index'  

And to finish here is what the console show when I try to post an article

Started GET "/post" for 127.0.0.1 at 2016-04-10 14:24:56 +0200  Processing by ArticlesController#create as HTML     (0.2ms)  BEGIN     (0.2ms)  ROLLBACK    Rendered articles/create.html.haml within layouts/application (1.4ms)  Completed 200 OK in 9ms (Views: 4.9ms | ActiveRecord: 0.4ms)      Started POST "/articles" for 127.0.0.1 at 2016-04-10 14:25:10 +0200  Processing by ArticlesController#index as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"FMQmKvZ1t98ZE21VaiBQhm0jKJ9x9BwkXFbh4obfi3Qea0Zax5dgGirfpgcAiQA464GMD2+Qv/eGYrmvEoTZBQ==", "article"=>{"title"=>"Post", "body"=>"New Article test"}, "commit"=>"Publier"}    Article Load (0.6ms)  SELECT  "articles".* FROM "articles"  ORDER BY created_at DESC LIMIT 5 OFFSET 0     (0.4ms)  SELECT COUNT(*) FROM "articles"    Rendered articles/index.html.haml within layouts/application (3.4ms)  Completed 200 OK in 7ms (Views: 5.3ms | ActiveRecord: 1.0ms)  

I don't understand why the new article won't save. Does anyone understand why ?

Rails http caching: Setting cache-control header not caching (not returning 305 not modified response) http page

Posted: 10 Apr 2016 05:27 AM PDT

I am on Rails 4 and learning http caching from here https://devcenter.heroku.com/articles/http-caching-ruby-rails

I am trying to set cache-control header with rails expires_in method. please see this link https://devcenter.heroku.com/articles/http-caching-ruby-rails#time-based-cache-headers

i am able to set cache-control value to max-age = 180. however when i refresh my web page again within 180 seconds after previous http request the request is hit to the rails entire stack again. i was expecting rails to return 305 not modified response because the cache-control header max-age value is set to 180 seconds.

Am i missing something here??

Rails devise routing prevents rake db:create working properly on test environment

Posted: 10 Apr 2016 05:27 AM PDT

I have a weird problem with my Rails 4 app. I'm using devise gem. I wrote the following code in routes.rb.

devise_for :users, controllers: {    confirmations: 'users/confirmations',    passwords: 'users/passwords',    registrations: 'users/registrations',    sessions: 'users/sessions',    unlocks: 'users/unlocks',  }  

Everything works fine in development mode, except in test environment. When I hit bundle exec rake db:create RAILS_ENV=test --trace in my iTerm2, it throws an error. I followed the trace and it came to the line for the above code in routes.rb.

I tried again after commenting out those lines and it worked. What is the possible cause for this issue?

Thanks in advance.

FYI, I'm using Sequel instead of ActiveRecord for this Rails 4 app, so instead of regular devise gem, sequel-devise and sequel-devise-generators are used that are specifically written for Sequel.

Deploying Rails-application on Ubuntu server using Capistrano gem

Posted: 10 Apr 2016 05:22 AM PDT

I try to deploy my rails application on local virtual machine which runs ubuntu 14 LTS. I use nginx and phusion passenger. Also, I use capistrano gem for deployment.

I added my local ssh key to virtual machine's authorized keys.
Also i have no problem connecting to my virtual machine via ssh like that:
ssh neil@192.168.0.8

However when I write:

bundle exec cap production deploy    

I get the following error:

cap aborted!    Net::SSH::Disconnect: connection closed by remote host    EOFError: end of file reached    Tasks: TOP => rbenv:validate  

My deploy.rb file:

server "192.168.0.8", port: 80, roles: %i(:web :app :db), primary: true    set :log_level, :debug      set :application, "mySimpleBlog"    set :repo_url, "git@github.com:NeilAlishev/mySimpleBlog.git"    set :user,            "neil"    set :linked_files, fetch(:linked_files, []).push("config/database.yml", "config/secrets.yml")    set :linked_dirs, fetch(:linked_dirs, []).push("log", "tmp/pids", "tmp/cache", "tmp/sockets",    "vendor/bundle", "public/system", "public/uploads")    set :deploy_to,       "/home/#{fetch(:user)}/src/#{fetch(:application)}"      set :rbenv_type, :user    set :rbenv_ruby, "2.2.4"    set :rbenv_prefix, "RBENV_ROOT=#{fetch(:rbenv_path)} "\    "RBENV_VERSION=#{fetch(:rbenv_ruby)} #{fetch(:rbenv_path)}/bin/rbenv exec"    set :rbenv_map_bins, %w(rake gem bundle ruby rails)    set :rbenv_roles, :all      namespace :deploy do      desc "Restart application"      task :restart do        on roles(:app), in: :sequence, wait: 5 do          execute :touch, release_path.join("tmp/restart.txt")        end      end        after :publishing, "deploy:restart"      after :finishing, "deploy:cleanup"    end  

My deploy/production.rb file:

set :stage, :production    server "192.168.0.8", user: "neil", roles: %w(web app db)    role :app, %w(neil@192.168.0.8)    role :web, %w(neil@192.168.0.8)    role :db,  %w(neil@192.168.0.8)   

My nginx.conf file:

server {    listen 80;    server_name 192.168.0.8;    charset utf-8;    rails_env production;    passenger_enabled on;    root /home/neil/mySimpleBlog/current/public;    }    

routing error using omniauth and custom user model

Posted: 10 Apr 2016 05:23 AM PDT

I have a custom User model and authentication via omniauth-facebook and omniauth-vkontakte. The authentication is needed to leave comments to Post model and review to Book model. So I defined a sessions_controller.rb:

def create      user = User.from_omniauth(request.env['omniauth.auth'])      cookies[:user_id] = user.id      redirect_to root_path  end  

and in show.html.erb of both the Book and Post models I have the following:

<div>      <p>Only signed in users can leave comments/reviews.       Please sign in via <%= link_to 'Facebook', 'auth/facebook' %> or      <%= link_to 'VK', 'auth/vkontakte' %> </p>  </div>   

and in routes.rb I have this:

get 'auth/:provider/callback', to: 'sessions#create'  

the console returns the following error: ActionController::RoutingError (No route matches [GET] "/books/auth/facebook")

How to find spree accoutn view source code

Posted: 10 Apr 2016 05:36 AM PDT

recently I had a need to modify a view template of the Spree e-commerce. According to the guides, I need to run bundle show spree to view current location of the spree gem and then copy view templates from there. https://guides.spreecommerce.com/developer/view.html But the target folder does not contain views folder << account >>, also I did a search for particular word 'favourites', no results. Maybe I need to install other gem, like spree_frontend or other? Can someone please help to find views to change?

Capybara Poltergeist ActionCable testing

Posted: 10 Apr 2016 04:30 AM PDT

I wrote an application (with rails 5.0.0beta3) which has several live updates using ActionCable.
So I wanted to test what I wrote. I added poltergeist to my Gemfile and bundled it and ran an example.
Javascript is correctly executed.

But when sprocket tries to add action_cable it fails:

TypeError: 'undefined' is not a function (evaluating 'this.events[eventName].bind(this)')  TypeError: 'undefined' is not a function (evaluating 'this.events[eventName].bind(this)')      at http://127.0.0.1:63829/assets/application-2d6ae1aa6efc25d4e4902c5f2d384b5473eb4bdcc9489a9857608e6fe9952eb5.js:12789  ...  

I think this comes from this line right here

If this is not the way to test action cable, how should I do that?

Rails and Paperclip storing images in a specific path sets wrong URL

Posted: 10 Apr 2016 04:54 AM PDT

I want to store my images using the normal file storage adapter.

This is my PAPERCLIP_STORAGE_OPTS:

PAPERCLIP_STORAGE_OPTS = {      :styles => { :thumb => '170x170!#', :medium => '450x300!>', :large => '600x400!>',:desktop => '750x300!>'},      :convert_options => { :all => '-quality 100' },      :processor       => [ :papercrop ],      :path => "/opt/www/myapp/images/:class/:attachment/:id_partition/:style/:filename"    }  

This is my model :

class User < ActiveRecord::Base      attr_accessor :PAPERCLIP_STORAGE_OPTS      has_attached_file :user_photo, PAPERCLIP_STORAGE_OPTS_THUMB  

When a user uploads a photo - it actually does store the image in the correct location on my system:

/opt/www/myapp/images/users/user_photos/000/000/050/original/picture  

However when I go to show the image, like this :

<%=image_tag current_user.user_photo.url(:thumb), :height=> "30", :width=> "30" %>  

The image is not found, and in my logs I see the image request at this URL:

ActionController::RoutingError (No route matches [GET] "/system/users/user_photos/000/000/050/thumb/picture"):  

And the full URL created is :

https://www.myapp.com/system/users/user_photos/000/000/050/thumb/picture?1460285803 - which doesnt resolve.

How can I configure paperclip to allow my images to be stored in this particular url /opt/www/myapp/images/ and still be accessed and linked to correctly through Paperclip in my rails app?

Rails, edit link will redirect but update button won't work

Posted: 10 Apr 2016 06:19 AM PDT

In my rails app I have this edit form that does not seem to work properly. If I enter the edit-site through any link, everything will look fine but the form submit button will not work. If I refresh the window it works fine.

Edit.html.erb

    <div class="alien-choice">          <h2 class="player_name"><%= current_user.username %></h2>          <p> Choose <span>0</span>/2 Power</p>        <%= form_for [@gameround, @currentplayer] do |f| %>            <% alleflares = @currentplayer.flares %>            <% alleflares.each { |val|               printAlien = Alien.find_by_title(val)          %>          <div class="alien_wrap">              <h3><%= printAlien.title  %> <span>[<%= printAlien.expansion.abbr   %>]</span></h3>                <label for="<%= printAlien.title %>">                  <div class="alien" style="background-image: url(<%= printAlien.avatar.url %>)">              </label>                <%= f.check_box(:aliens, { :multiple => true, :id => printAlien.title, :class => 'choosealiens'}, printAlien.title, nil) %>                </div>          </div>              <% } %>            </div>            <div class="actions">              <%= f.submit %>          </div>      <% end %>    <%= link_to 'Back', gameround_currentplayers_path %>  

The controller

class CurrentplayersController < ApplicationController    before_action :set_currentplayer, only: [:show, :edit, :update]      # GET /currentplayers    # GET /currentplayers.json    def index      @currentplayers = Currentplayer.all    end      # GET /currentplayers/1    # GET /currentplayers/1.json    def show      @gameround = Gameround.find(params[:gameround_id])      @currentplayer = @gameround.currentplayers.find(params[:id])        current_user    end      # GET /currentplayers/new    def new      @gameround = Gameround.find(params[:gameround_id])      @currentplayer = Currentplayer.new    end      # GET /currentplayers/1/edit    def edit        @gameround = Gameround.find(params[:gameround_id])        @currentplayer = @gameround.currentplayers.find(params[:id])      end      # POST /currentplayers    # POST /currentplayers.json    def create      @gameround = Gameround.find(params[:gameround_id])        @currentplayer = @gameround.currentplayers.create(currentplayer_params);        respond_to do |format|        if @currentplayer.save          format.html { redirect_to @gameround, notice: 'Currentplayer was successfully created.' }          format.json { render :show, status: :created, location: @currentplayer }        else          format.html { render :new }          format.json { render json: @currentplayer.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /currentplayers/1    # PATCH/PUT /currentplayers/1.json    def update        @gameround = Gameround.find(params[:gameround_id])        @currentplayer = @gameround.currentplayers.find(params[:id])          if @currentplayer.update(currentplayer_params)          redirect_to gameround_currentplayer_path          else          render 'edit'        end        end      # DELETE /currentplayers/1    # DELETE /currentplayers/1.json    def destroy       @gameround = Gameround.find(params[:gameround_id])        @currentplayer = @gameround.currentplayers.find(params[:id])      @currentplayer.destroy      respond_to do |format|        format.html { redirect_to '/play', notice: 'Currentplayer was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_currentplayer        @currentplayer = Currentplayer.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def currentplayer_params        params.require(:currentplayer).permit(:log_id, :flares, :winner, :bases, :gameround_id, aliens:[])      end  end  

config.routes

Rails.application.routes.draw do        resources :gamerounds do       resources :currentplayers    end   

Active Merchant paypal recurring payments

Posted: 10 Apr 2016 04:51 AM PDT

I am using Active Merchant gem to handle payments through the site. But now i want to make these payments recurring, on a monthly basis. Is there a way using active merchant or?

subscription_controller.rb

    class SubscriptionsController < ApplicationController    def new      @home_page = true      @white = true      @subscription = Subscription.new(token: params[:token])      if !logged_in?        redirect_to signup_url      end    end      def create      @subscription = Subscription.new(subscription_params)      @subscription.remote_ip = request.remote_ip      @subscription.user_id = current_user.id      if @subscription.save        if @subscription.purchase          @subscription.send_thank_you_email          redirect_to thankyou_path        else          raise ActiveRecord::Rollback          flash[:notice] = "It seems something went wrong with the paypal transaction. Please check that your credit card is valid and has credit in it and try again."          redirect_to :back        end      else        flash[:notice] = "Something went wrong with marking your purchase as complete. Please contact support to check it out."        redirect_to :back      end    end      def purchase      response = GATEWAY.setup_purchase(999,        ip: request.remote_ip,        return_url: new_subscription_url,        cancel_return_url: root_url,        currency: "USD",        items: [{name: "Order", description: "Recurring payment for ******", quantity: "1", amount: 999}]      )      redirect_to GATEWAY.redirect_url_for(response.token)    end      def thank_you      @home_page = true      @white = true    end      private        def subscription_params        params.require(:subscription).permit(:token)      end      end  

subscription.rb model

def purchase      response = GATEWAY.purchase(999, express_purchase_options)      response.success?    end      def token=(token)      self[:token] = token      if new_record? && !token.blank?        # you can dump details var if you need more info from buyer        details = GATEWAY.details_for(token)        puts details.params["PayerInfo"]["PayerName"].inspect        self.payer_id = details.payer_id        self.first_name = details.params["PayerInfo"]["PayerName"]["FirstName"]        self.last_name = details.params["PayerInfo"]["PayerName"]["LastName"]      end    end      # send thank you email    def send_thank_you_email      UserMailer.thank_you(self).deliver_now    end      private      def express_purchase_options      {        :ip => remote_ip,        :token => token,        :payer_id => payer_id      }    end  

production.rb environment

config.after_initialize do      ActiveMerchant::Billing::Base.mode = :production      ::GATEWAY = ActiveMerchant::Billing::PaypalExpressGateway.new(        :login => ENV['PAYPAL_LOGIN'],        :password => ENV['PAYPAL_PASSWORD'],        :signature => ENV['PAYPAL_SIGNATURE']      )    end  

Switching from Postmark to Postfix

Posted: 10 Apr 2016 07:14 AM PDT

We want to switch from Postmark to Postfix, but with postfix the mail with the attachment(pdf file) is arriving as garbage:

" -- Date: Sun, 10 Apr 2016 13:17:56 +0300 Mime-Version: 1.0 Content-Type: application/pdf; charset=UTF-8; filename=test_order1460278254278.pdf Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=test_order1460278254278.pdf Content-ID: <570a2854317a9_1c6f12f77f841854@app1.mail> JVBERi0xLjQKJeLjz9MKNSAwIG9iago8PC9CYXNlRm9udC9QV1dNR1QrQXJp YWxNVC9EZXNjZW5kYW50Rm9udHNbNiAwIFJdL1R5cGUvRm9udC9TdWJ0eXBl L1R5cGUwL0VuY29kaW5nL0lkZW50aXR5LUgvVG9Vbmljb2RlIDkgMCBSPj4K ZW5kb2JqCjEwIDAgb2JqCjw8L0Jhc2VGb250L1dYSkRSSytMdWNpZGFTYW5z LVR5cGV3cml0ZXJCb2xkL0Rlc2NlbmRhbnRGb250c1sxMSAwIFJdL1R5cGUv Rm9udC9TdWJ0eXBlL1R5cGUwL0VuY29kaW5nL0lkZW50aXR5LUgvVG9Vbmlj b2RlIDE0IDAgUj4+CmVuZG9iagoxNSAwIG9iago8PC9CYXNlRm9udC9UaW1l "

This is my code:

    class UserMailer < ActionMailer::Base        default :from => "mailer@xodapp1.com"        default :bcc => "do_not_reply@xodapp1.com"        default :reply_to => "do_not_reply@xodapp1.com"          def send_email(agent, customer, subject, body, mail_to = nil, mail_cc = nil, url_attachment = nil , name_attachment = nil)          #attachments[name_attachment] = {:content => open(url_attachment).read, :mime_type =>  MIME::Types.type_for(name_attachment).first}  unless url_attachment.nil?          mail_to = !mail_to.nil? ?  mail_to : "\"#{customer.name}\" <#{customer.email}>"          mailers_to = mail_to.split(',')            mail_cc = !mail_cc.nil? ?  mail_cc.split(',') : agent.email          if [nil, []].include?(mail_cc)            mail_cc = UserMailer.default[:bcc]          end            body = "Copy attached" if body.nil? || body.empty?            mail_obj = mail(:to => mailers_to,               :from => "\"#{agent.name}\" <mailer@xodapp1.com>",               :bcc =>  mail_cc,               :subject => subject,               :content_type => "text/html",               :body => body.html_safe,               :reply_to => "#{!agent.email.nil? ? agent.email : UserMailer.default[:reply_to]}"          )          mail_obj.attachments[name_attachment] =  open(url_attachment).read unless url_attachment.nil?          return mail_obj        end  end  

Thanks in advance

Adrian

Select only year part from dates in a table without duplicates [duplicate]

Posted: 10 Apr 2016 03:37 AM PDT

This question already has an answer here:

I have a huge table with various data, and one column represents date. It's date data type. I want to assign variable with all possible years from that date without any duplicates.

For example:

|   dates    |  +------------+  | 2016-04-04 |  | 2016-05-05 |  | 2016-06-06 |  | 2017-05-02 |  | 2017-01-05 |  | 2018-07-05 |  

I want my variable to look something like this:

@years = [2016, 2017, 2018]  

how to add a new association to library model

Posted: 10 Apr 2016 04:33 AM PDT

I am using merit library in rails. And hope to add an association in Merit::Score::Point so that it has a has_one association with another model call ScoreWorkflow.

Below is my code. In this code, I hope to add an association so that I can add a has_one to the library model. However it does not work. Is there anything that like this that I can put some function/assoication to a library model. Thanks.

module Merit    module Score      class Point < Point        has_one :score_workflow      end    end  end  

Rails 4 - either or if statement

Posted: 10 Apr 2016 05:47 AM PDT

I have an organisation model, which has an attribute called org_type. In my organisation form, I ask users to specify whether their org type is university, college or other kinds of organisation. In my show page, I want to show some text if the org type is university or college.

I can't get the either or function working. If I just ask to check one org type, such as below, it works fine:

<% if @organisation.org_type == 'University' %>  

If I ask for either org type, it shows everything even where the test org is 'other':

<% if @organisation.org_type == 'University' or 'College' %>  

The above doesn't work. It shows the text where the org type is 'other'.

Can anyone see what I've done wrong?

Apache Reverse Proxy Unix Socket

Posted: 10 Apr 2016 04:37 AM PDT

I am trying to setup ProxyPass in Apache 2.4.7 using unix sockets to a puma server for a rails application. I keep receiving a 500 Internal Error. When I check the apache logs I receive this message:

No protocol handler was valid for the URL /. If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule.

This is my proxy config in apache

ProxyPass / unix:///home/rails/rp/tmp/sockets/puma.sock|http://127.0.0.1/  ProxyPassReverse / unix:///home/rails/rp/tmp/sockets/puma.sock|http://127.0.0.1/  

If I setup a Proxy Pass on a regular tcp port like this, it works fine.

ProxyPass / http://127.0.0.1:9292  ProxyPassReverse / http://127.0.0.1:9292  

Any help is appreciated, let me know if you need anymore information.

How to correctly associate a model with 2 different objects?(Rails 4)

Posted: 10 Apr 2016 01:36 AM PDT

Before I ask my question, I will give some context.

In my Rails 4 app, I have 3 models in question.

Clubs has_many Teams.   Teams belong_to Clubs  Clubs has_many Schedules.   Schedules belong_to Clubs.   

The Relevant Columns for Teams in the Database:

:win(integer)  :loss(integer)  :tie(integer)  

The Relevant Columns for Schedules in the Database:

:team1  :team2  

The schedule object is supposed to show 2 teams versus each other. In the form for the schedule object, I will make Club.teams available in 2 separate drop-down boxes, so the user can select :team1 and :team2.

Upon the creation of a Schedule object, I'd like to make a toggle box available which you can click on later to state which team won the match.

Example Setup for the div of a Schedule Object:

Team 1                    |(Box1)|(Box2)|(Box3)|                       Team 2  

If Box1 is clicked for example, that would mean Team 1 won and I would automatically adjust the Win/Loss/Tie Columns in the Teams Table(Increase :win by 1 for Team 1 and increase :loss by 1 for Team 2). Box2 means tie and Box2 means Team 2 won. This will be done by ajax.

Finally, for my question, how do I associate :team1 and :team2 columns in the Schedule object with the appropriate Team objects in the Teams table in order to manipulate their columns with the toggle box?

Is there any way in which each do can go to the infinte loop in ruby

Posted: 10 Apr 2016 12:40 AM PDT

I am new to ruby, i am trying to create an endless loop in ruby,is there any way to create an endless using each do . I know by using for,while we can achieve it.

Rails: Store (merge) parameter after Devise Sign In

Posted: 10 Apr 2016 03:32 AM PDT

I have a form that should be submitted after Sign In but all the viewers can see and fill the form. So, I save the parameters in a session variable. After Sign In, I store the parameters successfully. The problem is that I want to add the user_id (which is foreign key) and store it beside the other parameters (before Sign In, the user_id is unknown). Part of my Controller's code:

def create    if current_user.nil?          session[:trip] = params          redirect_to new_user_registration_path    else          @trip = Trip.new(trip_params)          respond_to do |format|            if @trip.save  ...  private    def set_trip    @trip = Trip.find(params[:id])  end      def trip_params    params.require(:trip).permit(:from, :to, :departure_date, :arrival_date, :user_id)  end  

As I mentioned, this code stores the new form parameters successfully. To add (insert or merge) the current_user.id, I tried these different ways separetely:

@trip = Trip.new(trip_params.merge(user_id: => current_user.id)

@trip = Trip.new(trip_params)  @trip.user_id = current_user.id  

@trip = current_user.Trip.new(trip_params)

@trip = current_user.trips.new(trip_params)

I've tested all of these ways but still the user_id have not been saved!! Please, help me to understand the problem and its solution for Rails4.

Rails MVC - Should database search logic go in the model or the controller

Posted: 10 Apr 2016 04:59 AM PDT

I would like to make sure my code is properly organized/designed according to the following paradigms/patterns:

- Model View Controller

- Rails Convention over Configuration

- Skinny Controller, Fat Model

I have listed them here in the order I think is most important.


My issue

After reading several articles, in particular this one and this one too, I started to move some of the logic in my controllers, to my models.

However, I can't decide whether or not to move my searching logic (explained in depth, later) from the controller to the model, even after reading more posts/articles like these: MVC Thinking, and Model vs. Controller, Separating concerns and many more not listed here.


The scenario

View

Two pages:

  • 1 page contains a text field and submit button which sends the user's input as an argument in params in a POST request to the second page.

  • The second page simply renders each neatObject in a given array, let's call it @coolList.

Controller

  • A method, let's call it awesomeSearch, is invoked when the second page receives a POST request. (Thanks to Rails Routing)
  • awesomeSearch should take the user's input, available as params[:searchString], and work with the NeatObject model to build the @coolList and make that list available for the view to render.

Model

  • The NeatObject model handles requests from controllers and returns neatObjects back to those controllers.

  • The NeatObject model defines the relationship between neatObjects and other tables in our database.

Database

These are the attributes that make up each neatObject according to our database:

  • id - int
  • description - string
  • address - string
  • date_created - timestamp

What's Missing?

How the controller works with the model to get matches for the user's input.

This is the part I am confused about. The logic itself is very simple, but I am not sure which pieces belong in the model, and which pieces belong in the controller.

  • Should the controller pass the search string to the model, and the model pass back the results?

  • Should the controller ask the model for all of the neatObjects, then only keep the ones that match?

  • Is the solution a little of both?

To be able to ask questions about specific bits of the logic, I'll next outline the search process with more detail.


The search logic in depth

The process involves finding neatObjects that match the search string. It would be impossible to move on without defining what we consider matches for neatObjects. To keep things very simple, we will say that:

A neatObject matches a search string if the search string is contained within its description or its address, ignoring case and leading/trailing whitespace.

This definition is not guaranteed to be permanent. There are several things that may change our definition. We may need to test against more attributes than just address and description, perhaps if the database guys add a new important attribute, or the UI guys decide users should be able to search by ID. And of course, the opposite of these scenarios would mean we need to remove an attribute from the list of attributes we are testing. There are many situations that could change our definition of a match. We could even have to add or remove logic, perhaps if it is decided that we should only test the first word in the description attribute, or perhaps if we should no longer ignore case.

Now we know what defines a match and we know that our definition may change. Now we can more concretely define the search process.

Here is an outline of the steps:

  1. Get a reference to all neatObjects
  2. Loop through each neatObject, putting each individual one through the match test
    1. Test passes - add/keep neatObject in results list
    2. Test fails - do not keep neatObject for results
  3. Make results available to the view

I will reference these steps as I show possible implementations.


Implementation

The search functionality can easily be implemented in either the NeatObject model, or the controller serving the view.

Normally, I would just write all of the logic in the controller, but after I learned about the "Skinny controller, Fat model" design, I thought it definitely applied in this situation. This article in particular made me think to reorganize my code, after I saw the author had implemented a "search-like" function in the model. The author's function did not handle user input though, so I was wondering how it should be handled.

This is how I would have written the code before learning about "SCFM":

Search logic in controller:

#searches_controller.rb      #This is the method invoked when second page receives POST request  def search      @neatObjects = NeatObjects.all.to_a          @neatObjects.delete_if {           |neatObject| !matches?(neatObject, params[:searchString])      }  end    def matches?(neatObject, searchString)      if((neatObject.description.downcase.include? searchString.downcase) ||         (neatObject.address.downcase.include? searchString.downcase))          return true      end      return false  end  

This method gets its reference to all of the neatObjects (Step 1) by calling .all() on the NeatObject model. It uses the array function delete_if to perform the match test on each neatObject, and only keeps those that pass (Step 2). Step 3 is accomplished automatically automatically since we store our results in an instance variable in the controller which serves the view.

Placing the logic in the controller is very straight-forward, but when considering the "SCFM" design pattern, it seems very illogical.

I've written another option, in which the controller sends the user's input to a function in the model, which will return the the neatObjects which match the input.

Search logic in Model

#NeatObject.rb      def self.get_matches_for(searchString)      all.to_a.delete_if { |neighborhood| !matches?(searchString, neighborhood) }  end    def self.matches?(phrase, neighborhood)      fields = [neighborhood.name, neighborhood.address]        fields.map!(&:downcase)      phrase.downcase!        fields.each do |field|          if (              (phrase.include? field) ||              (field.include? phrase)             )              return true          end      end        return false  end    

This method gets the complete list of neatObjects with all() (Step 1). Just like the first method, the model method uses delete_if to remove array elements (neatObjects) that don't meet a certain criteria (passing the match test) (Step 2). In this method, the controller serving the view would call get_matches_for on the NeatObject model, and store the results in an instance variable (Step 3), like this: @neatObjects = NeatObject.get_matches_for( params[:searchString] )

I do think that the model option is cleaner, and slightly more maintanable, but I'll go more in depth in the following section.


Concerns

I can see pros and cons to both the model method and the controller method, but there are things that I'm still unsure about.

When I read over that article I've referenced several times (just like I did here), it was very logical that the model defined a function to return the recently added people.

The controller didn't have to implement the logic to determine if a person had been recently added. It makes sense that the controller shouldn't, because that is dependent on the data itself. There might be a completely different implementation of the "recency" test for messages. The recent people might include people added this week, while recent messages are only those messages sent today.

A controller should just be able to say People.find_recent or Message.find_recent and know it got the correct results.

  • Is it correct to say the find_recent method could also be modified to take in a time symbol, and return objects for different time periods? Ex - People.find_in_time( :before_this_month ) or Messages.find_in_time( :last_year ). Does that still follow the MVC pattern and Rails convention?

  • Should a controller be able to find matches for user input with NeatObject.get_matches_for( searchString )?'

I think the matching logic belongs in the model, because there are certain/specific attributes that are used in testing, and those attributes are different depending on the data. We might have different attributes for different tables, and those attributes definitely shouldn't be defined by the controller. I know the controller depends on the model, not the other way around, so the model must define those attributes, even if the rest of the logic is in the controller.

  • And if the model defines the attributes that are used when searching, why shouldn't it define the entire search function?

The above text explains why I think the model should handle the searching logic and expresses the majority of my questions/concerns, however I do have some opinions favoring the other option.

  • If the model is concerned only with the data, how can one justify passing user input to it?

If the controller doesn't handle the search logic, it still needs to send the user's input to the model. Does it clean it up before it sends it? (Removing leading/trailing whitespace and downcasing the string.) Does it just send the exact input it got from the user?

  • Where is the testing done to make sure the input is not malicious?

Some of my biggest questions:

  • Does the answer for where the logic goes change for each case?

If the search/matching process was simpler, would the code's place change? For example, if the searching was simpler:

  • If the only attribute being tested was the address and that was unlikely to change, would we just handle the search with the controller?

  • If we were making an advanced search feature, where the user decided which attributes to include in the search and also controlled some other factors, there would be a lot of user input just to define the arguments to the search function. Would that be too much logic or user input to place in the model?


In conclusion

  • How can I always be sure that I am putting logic in the right place (MVC)?
  • For my specific case, with this data and this search/match process, how should I organize the code?
  • What guidelines can be followed when you find a gray area, or are unsure about where logic belongs?

Trying to associate 2 models with has_many through using formtastic

Posted: 09 Apr 2016 11:56 PM PDT

Hi I am trying to make an e-commerce website using rails 4 but I got stuck in a problem. I have a model named cloth that will have all the items that will be sold in the site, but I want to only declare once the sizes and colors for best functionality and filtering, so I have to associate these models to the cloth's somehow, and doing research I found that with has_many through was the best one, so my models are like:

Cloth:

class Cloth < ActiveRecord::Base    belongs_to :admin    belongs_to :brand    belongs_to :category      has_many :sis    has_many :cos    has_many :sizes, :through => :sis    has_many :colors, :through => :cos    has_many :images  end  

Color:

class Color < ActiveRecord::Base    has_many :cos    has_many :cloths, :through => :cos  end  

Size:

class Size < ActiveRecord::Base    has_many :sis    has_many :cloths, :through => :sis  end  

As it can be seen I added models co and si for doing the association, the problem is when I try to make a new cloth. I don't know if using the formtastic has something to do with the problem so here is the code for the part on declaring the colors and sizes in the form:

<div class="form-group">      <%= f.input :sizes, :as => :check_boxes, :label => "Selecciona las tallas en las que está disponible", :collection => Hash[Size.all.map { |size| [size.letter, size.id] }] %>  </div>  <div class="form-group">      <%= f.input :colors, :as => :check_boxes, :label => "Selecciona los colores en los que está disponible", :collection => Color.all %>  </div>  

They render perfectly and the size works perfectly, but the problem is in the color, it can be selected but the "co" doesn't get safe in the db, as it can be seen in the server log:

The si get written in db, but the co doesn't even appear, also I think it has something to relate to the "Unpermitted parameter: color_ids"

I hope you can help me, and I apologize if my english is not perfect.

Thanks

P.S. If you have a good method for filtering the clothes in the index with ajax or something like that. When selecting a size like "S" in a dropdown, and only display clothes that has size "S", will be much appreciated.

rails additional params to controller

Posted: 09 Apr 2016 11:02 PM PDT

I want to pass a value which the model does not have

<div class="form-group">      <%= form_for(@car) do |f| %>        <%= f.label :name, "Add New Tags:" %>        <%= f.text_field :name, class: "form-control" %>        <%= hidden_field_tag :additional_parms, value: 'some_value' %>        <%= f.submit "Add Car",:id => 'tag_btn', class: "btn btn-primary" %>      <% end %>  </div>  

I am using hidden field to the add the value the to params but when I look at the log, the additional_params is not in the params

Custom Marker in gmaps4rails won't appear

Posted: 09 Apr 2016 11:26 PM PDT

I tried following the guide in https://github.com/apneadiving/Google-Maps-for-Rails, however my custom icons still do not load.

 @hash = Gmaps4rails.build_markers(@terminals) do |terminal, marker|            marker.lat terminal.latitude            marker.lng terminal.longitude           marker.picture({              "url" => "/assets/marker.png",              "width" =>  30,                      "height" => 30              })          end  

The image marker.png is in assets/images.

Building the map:

<script type="text/javascript">  handler = Gmaps.build('Google');  handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){    markers = handler.addMarkers(<%=raw @hash.to_json %>);    handler.bounds.extendWith(markers);    handler.fitMapToBounds();    handler.getMap().setZoom(13);    handler.getMap().setOptions({styles: [{"featureType":"water","stylers":[{"saturation":43},{"lightness":-11},{"hue":"#0088ff"}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"hue":"#ff0000"},{"saturation":-100},{"lightness":99}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"color":"#808080"},{"lightness":54}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#ece2d9"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"color":"#ccdca1"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#767676"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","stylers":[{"visibility":"off"}]},{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#b8cb93"}]},{"featureType":"poi.park","stylers":[{"visibility":"on"}]},{"featureType":"poi.sports_complex","stylers":[{"visibility":"on"}]},{"featureType":"poi.medical","stylers":[{"visibility":"on"}]},{"featureType":"poi.business","stylers":[{"visibility":"simplified"}]}]});  });  </script>  

The map:

    <div id="map"class="col-md-8" style="height: 100vh; background-color: #E4E2E1;">      </div>  

How it appears: enter image description here

How it looks without marker.picture in the controller: enter image description here

Unable to invoke the before_save callback for each user in console in rails

Posted: 10 Apr 2016 12:38 AM PDT

I am following the Michael Haartl tutorial on Ruby on Rails. The user created before developing the signin function need to be assigned a remember token. For that, I use the following code in console:

User.all.each { |user| user.save(validate: false) }  

Since I have:

before save :create remember token  

in app/models/user.rb, this should create a remember token, but I get the following error on running this:

NameError: undefined local variable or method `base64' for     #<User:0x00559aefda7f20>  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activemodel-4.2.4/lib/active_model/attribute_methods.rb:433:in `method_missing'  from /home/shivani/myapp/app/models/user.rb:13:in `create_remember_token'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:432:in `block in make_lambda'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:164:in `call'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:164:in `block in halting'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:504:in `call'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:504:in `block in call'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:504:in `each'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:504:in `call'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:92:in `__run_callbacks__'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:778:in `_run_save_callbacks'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.4/lib/active_record/callbacks.rb:302:in `create_or_update'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.4/lib/active_record/persistence.rb:120:in `save'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.4/lib/active_record/validations.rb:37:in `save'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.4/lib/active_record/attribute_methods/dirty.rb:21:in `save'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activerecord-4.2.4/lib/active_record/transactions.rb:286:in `block (2 levels) in save'  ... 14 levels...  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/commands/console.rb:9:in `start'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:68:in `console'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:39:in `run_command!'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/commands.rb:17:in `<top (required)>'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:274:in `require'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:274:in `block in require'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:240:in `load_dependency'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:274:in `require'  from /home/shivani/myapp/bin/rails:9:in `<top (required)>'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:268:in `load'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:268:in `block in load'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:240:in `load_dependency'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:268:in `load'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'  from /home/shivani/.rbenv/versions/2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'  

Please help! Contents of user.rb:

class User < ActiveRecord::Base       has_secure_password      before_save { self.email = email.downcase }      before_save :create_remember_token      private      def create_remember_token         self.remember_token = SecureRandom.urlsafe Base64      end      validates :name, presence: true, length: { maximum: 50 }      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i      validates :email, presence: true, length: { maximum: 255 },                  format: { with: VALID_EMAIL_REGEX },                  uniqueness: { case_sensitive: false }        validates :password, presence: true, length: { minimum: 6 }      end  

No comments:

Post a Comment