Wednesday, June 8, 2016

rails4 behavior based on link_to is nil | Fixed issues

rails4 behavior based on link_to is nil | Fixed issues


rails4 behavior based on link_to is nil

Posted: 08 Jun 2016 07:01 AM PDT

There is a website attr on product_lead table which is optional. If it's present then I wanna turn @produc_lead.lead into a link, but if it's not it should be plain text.

If I use the code below and the website is nil then the link points to the page the user is currently on. If I do it with @product_lead.try(:website), it's gonna be the same. But as I mentioned I would like to have plain text over link in this case.

<%= link_to @product_lead.website, target: "_blank" do %>    <%= @product_lead.lead %>  <% end %>  

After playing around I fell back to the following solution, but it's terrible. Any better ideas?

<% if @product_lead.website %>    <%= link_to @product_lead.website, target: "_blank" do %>      <%= @product_lead.lead %>    <% end %>  <% else %>    <%= @product_lead.lead %>  <% end %>  

How to create has_many association with "includes" and "where" conditions

Posted: 08 Jun 2016 06:53 AM PDT

Here is the situation: a store has many products, and can join multiple alliances. But the store owner may not want to display certain products in some alliances. For example, a store selling computers and mobile phones might want to display only phones in a "Phone Marts".

By default, all products in the store will be displayed in all alliances one shop joins. So I think building a product-alliance blacklist (I know it's a bad name...any ideas?) might be a convenient way.

The question is: how to create a "has_many" to reflect such relations like the behaviours of function shown_alliances and shown_products?

I need this because Car.includes(:shop, :alliances) is needed elsewhere, using functions make that impossible.

Product:

class Product < ActiveRecord::Base    belongs_to :store    has_many :alliances, -> { uniq }, through: :store    has_many :blacklists      def shown_alliances     alliances.where.not(id: blacklists.pluck(:alliance_id))    end  end  

Store:

class Store < ActiveRecord::Base    has_many :products    has_many :alliance_store_relationships    has_many :alliances, through: :alliance_store_relationships  end  

Alliance:

class Alliance < ActiveRecord::Base    has_many :alliance_store_relationships    has_many :store, through: :alliance_store_relationships    has_many :products, -> { uniq }, through: :companies    has_many :blacklists      def shown_produtcts      @produtcts ||= produtcts.where.not(id: blacklists.pluck(:produtct_id))    end  end  

Blacklist:

class Blacklist < ActiveRecord::Base    belongs_to :produtct    belongs_to :alliance    validates :produtct_id, presence: true,                       uniqueness: { scope: :alliance_id }  end  

how can i give a condition if start time and end time display <p> with rails

Posted: 08 Jun 2016 06:39 AM PDT

model code

def current  result = where("starts_at <= :now and ends_at >= :now", now: Time.zone.now)  result = result.where("id not log_in_now (?)", hidden_ids) if hidden_ids.present?  result  

view

 <% unless @unit.starts_at  >  @unit.ends_at %>         <% unless ContestantVote.friendship_exists?(current_user, @unit )%>            <%= link_to '<i class="glyphicon glyphicon-erase"></i>&nbspVote '.html_safe, vote_url(:unit_id => @unit.id,:user_id => current_user.id, :contestant_id => contestant.id), :class=>"cg ts fx",:style => " text-decoration:none;position: relative;left: 84px",:rel=>"external" %>        <% end %>      <% end %>  

how to condition to display but it not working fine any help

nubbie in ruby on rails

Posted: 08 Jun 2016 06:38 AM PDT

I'm trying to make a toy system to learn rails, well, I'm with a doubt, can help me?

I am using devise to authenticate. However I will need two profiles within the system.

User and Professional.

User = devise basic information

Profisssional = will have to add various informations.

What better way to create these different profiles?

with a boolean in the model User = 0 User, 1 Professional.

or creating more 1 devise model?

or Another way

Remembering that I'll need to list (array) the registered professional later.

render two different model errors in JSON

Posted: 08 Jun 2016 06:40 AM PDT

I have a remote form, that essentially submits two forms in one. One for Address the other for User now what I'd like to do is render the errors in JSON.

I'm able to return the errors individually like this:

if current_user.errors.any? || !@address.save    respond_to do |format|      format.json { render json: @address.errors, status: :unprocessable_entity }    end  end  

now there's the case where they trigger an error on both User model and Address. How can I render both errors so @address.errors and current_user.errors. I've tried to merge them as hashes, but as they belong to ActiveModel::Errors it's unable to do so. An error usually returns like this if you inspect it:

#<ActiveModel::Errors:0x007fbe094edda0 @base=#<Address id: nil, street_address: "Lorem ipsum", city: nil, state: nil, zip_code: "0000", country: nil, user_id: 1, created_at: nil, updated_at: nil, latitude: 10.92876, longitude: 52.23023, trashed: false>, @messages={:zip_code=>["No zip code matches this"]}, @details={:zip_code=>[{:error=>:inclusion, :value=>"0000"}]}>  

so what I'm trying to figure out is if there's a way to merge this into one, so I can just return that.

Gemfile returning lot of dependecies

Posted: 08 Jun 2016 06:04 AM PDT

I wrote a project in Ruby on Rails and tried to deploy it. Here is the Gemfile:

source 'http://rubygems.org'  source 'http://gems.github.com'    gem 'rails', '4.2.6'    gem 'rake','0.8.7'    # Bundle edge Rails instead:  # gem 'rails', :git => 'git://github.com/rails/rails.git'    #gem 'mysql2', '0.2.6'  gem 'mysql2', '0.3.20'    # GUID generator  gem 'uuidtools', '2.1.2'    # Paperclip: for image resizing  gem 'paperclip', '2.4'    # Delayed job  gem 'delayed_job', '2.1.2'    # Typus, admin interface  gem 'typus', '3.0.2'    # set attribute value to nil if blank  gem "nilify_blanks", '1.0.0'    # ssl gem  gem "bartt-ssl_requirement", "~> 1.2.7", :require => 'ssl_requirement'    # for social login  gem 'omniauth', '0.2.0'    # to detect user location  gem 'geocoder', '1.1.0'    # use to sanitize html  gem 'sanitize', '2.0.1'    # captcha for registration  gem 'recaptcha', '0.3.1', :require => "recaptcha/rails"  # base 32  gem 'base32', '0.1.3'    # amazon s3  gem 'aws-s3', '0.6.2'    #json  gem 'json', '1.7.7'    # pagination  gem 'will_paginate', '3.0.pre2'    # jammit for asset packaging  gem 'jammit', '0.6.3'    gem 'oniguruma'    # Use unicorn as the web server  # gem 'unicorn'    # Deploy with Capistrano  # gem 'capistrano'    # To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+)  # gem 'ruby-debug'  # gem 'ruby-debug19'    # Bundle the extra gems:  # gem 'bj'  # gem 'nokogiri', "1.4.4.1"  # gem 'sqlite3-ruby', :require => 'sqlite3'  # gem 'aws-s3', :require => 'aws/s3'    # Bundle gems for the local environment. Make sure to  # put test-only gems in this group so their generators  # and rake tasks are available in development mode:  # group :development, :test do  #   gem 'webrat'  # end    gem "fb_graph", "1.9.5"    gem 'sitemap_generator', '2.1.8'    gem 'fastercsv', "1.5.5"    # to make it the same prior to 3.018 upgrade    gem 'addressable', "2.2.4"  gem 'arel', "6.0"  gem 'attr_required', '0.0.3'    gem 'cocaine', "0.2.0"  gem 'daemons', "1.1.0"    gem 'httpclient', '2.2.1'  gem 'i18n', '0.5.0'    gem 'mail', '2.5.4'    gem 'mime-types', '1.16'  gem 'multipart-post', '1.1.0'  gem 'nokogiri', '1.4.4'  gem 'oauth', '0.4.4'  gem 'open4', '1.2.0'  gem 'polyglot', '0.3.1'  gem 'pyu-ruby-sasl', '0.0.3.2'  gem 'rack', '1.6'  gem 'rack-mount', '0.6.13'  gem 'rack-oauth2', '0.9.2'  gem 'rack-test', '0.5.6'  gem 'rest-client', '1.6.1'  gem 'ruby-openid', '2.1.8'  gem 'treetop', '1.4.9'  gem 'tzinfo', '1.1'  gem 'xml-simple', '1.0.15'    

Then I ran bundle update to update the gem packages which weren't compatible with rails 4.2.6. I got this error:

Bundler could not find compatible versions for gem "activesupport":   In Gemfile:     rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6)    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6)    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6)    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6) x86-mingw32    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6) x86-mingw32    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6)    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6) x86-mingw32    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6)    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6) x86-mingw32    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6)    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6) x86-mingw32    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6) x86-mingw32    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6)    rails (= 4.2.6) was resolved to 4.2.6, which depends on       actionview (= 4.2.6) was resolved to 4.2.6, which depends on         activesupport (= 4.2.6) x86-mingw32    delayed_job (= 2.1.2) was resolved to 2.1.2, which depends on       activesupport (~> 3.0)    delayed_job (= 2.1.2) was resolved to 2.1.2, which depends on       activesupport (~> 3.0) x86-mingw32    paperclip (= 2.4) was resolved to 2.4.0, which depends on       activesupport (>= 2.3.2)    paperclip (= 2.4) was resolved to 2.4.0, which depends on       activesupport (>= 2.3.2) x86-mingw32    rack-oauth2 (= 0.9.2) was resolved to 0.9.2, which depends on       activesupport (>= 2.3)    rack-oauth2 (= 0.9.2) was resolved to 0.9.2, which depends on       activesupport (>= 2.3) x86-mingw32    

So I added gem 'activesupport', '4.2.6' to Gem file and ran bundle update again, but got same error. How can I fix it?

Rails, trying to create a specific hash, but it does not work the way it should

Posted: 08 Jun 2016 06:07 AM PDT

Every area has multiple area_attachments.

For some reason I want only the images to be saved into the hash into the following way

@area_hash =[]  @aa_hash=[]          @areas.each_with_index do |area, counter|            @area_hash[counter] = {}            @area_hash[counter][:localizations] = area.article_localizations              area.area_attachments.each_with_index do |aa, i|                 @aa_hash[i]={}                           @full = aa.image.full.url                @large_thumb = aa.image.large_thumb.url                @thumb = aa.image.thumb.url                @aa_hash[i] = {full: @full, large_thumb: @large_thumb, thumb: @thumb}            end              @area_hash[counter][:images] = @aa_hash        end  

The problem is the @area_hash[counter][:images] is the same at every area. having the attachments of the first area.

I know something is wrong with my loop, but I can't find out what exactly.

Thank you.

Disable enforce utf8 in a redmine form

Posted: 08 Jun 2016 05:57 AM PDT

I have a redmine installation running fine. I have an issue to disable the utf-8 enforcement tag when doing searches. This is because on my network there is a url policy check that will prevent me from opening the url containing the utf-8 enforcement parameter.

So I went to /usr/share/redmine/app/views/issues/index.html.erb and changed this line:

<%= form_tag({ :controller => 'issues', :action => 'index', :project_id => @project },              :method => :get, :id => 'query_form') do %>  

to this

<%= form_tag({ :controller => 'issues', :action => 'index', :project_id => @project },              :method => :get, :id => 'query_form', :enforce_utf8 => false) do %>  

but the utf8 enforcement parameter shows up

What am I doing wrong? Can I disable it on a global base?

Rails capistrano nginx error with deploy

Posted: 08 Jun 2016 05:53 AM PDT

I have same trouble with this...

this is my error :

/home/deploy/.rvm/gems/ruby-2.3.1/gems/capistrano-3.1.0/lib/capistrano/i18n.rb:4: warning: key :starting is duplicated and overwritten on line 6 Stage not set, please call something such as cap production deploy, where production is a stage you have defined.

This is tutorial what i used : https://gorails.com/deploy/ubuntu/14.04#ruby

This is my capfile,

require 'capistrano/setup'  require 'capistrano/deploy'    require 'capistrano/rails'  require 'capistrano/bundler'  require 'capistrano/rvm'  require 'capistrano/puma'  

1# Loads custom tasks from `lib/capistrano/tasks' if you have any defined. Dir.glob('lib/capistrano/tasks/*.cap').each { |r| import r }

this is my nginx.conf :

upstream puma {  server unix:///home/deploy/ipass/shared/tmp/sockets/appname-puma.sock;    }    server {  listen 80 default_server deferred;  1# server_name example.com;     root /home/deploy/ipass/current/public;   access_log /home/deploy/ipass/current/log/nginx.access.log;   error_log /home/deploy/ipass/current/log/nginx.error.log info;     location ^~ /assets/ {     gzip_static on;    expires max;    add_header Cache-Control public;     }     try_files $uri/index.html $uri @puma;  location @puma {    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    proxy_set_header Host $http_host;    proxy_redirect off;      proxy_pass http://puma;  }    error_page 500 502 503 504 /500.html;  client_max_body_size 10M;  keepalive_timeout 10;   }  

I dont know what i must give more... mb my database.yml

database.yml

    default: &default      adapter: mysql2      encoding: utf8      pool: 5      username: root      password: htmlkoi8r      socket: /var/run/mysqld/mysqld.sock      development:      <<: *default      database: ipass_dev    test:      <<: *default      database: ipass_test        production:      <<: *default      database: ipass_production  

gemfile

source 'https://rubygems.org'                  # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'              gem 'rails', '4.2.6'                # Servers              gem 'puma'              gem 'unicorn'                # AUTH              gem 'devise'              gem 'cancancan', '~> 1.10'                  # Translation gems              gem 'russian', '~> 0.6.0'                # ORM              gem 'mysql2', '0.4.4'              # gem 'pg'              gem 'seed_dump'              # gem 'ar-octopus'              # gem 'redis-rails'              # gem 'redis'                # Admin Panel              gem 'rails_admin'              gem 'rails_admin_flatly_theme', github: 'konjoot/rails_admin_flatly_theme'                # Forms              gem 'simple_form'              #gem 'tinymce-rails'              #gem 'tinymce-rails-langs'                  # Mail and contacts              gem 'mail_form'                # Other gems              gem 'slim'  #htmlslim                    # Use SCSS for stylesheets              gem 'sass-rails', '~> 5.0'              # Use Uglifier as compressor for JavaScript assets              gem 'uglifier', '>= 1.3.0'              # Use CoffeeScript for .coffee assets and views              gem 'coffee-rails', '~> 4.1.0'              # See https://github.com/rails/execjs#readme for more supported runtimes              # gem 'therubyracer', platforms: :ruby                # Use jquery as the JavaScript library              gem 'jquery-rails'              # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder              gem 'jbuilder', '~> 2.0'              # bundle exec rake doc:rails generates the API under doc/api.              gem 'sdoc', '~> 0.4.0', group: :doc                # Use ActiveModel has_secure_password              # gem 'bcrypt', '~> 3.1.7'                # Use Unicorn as the app server              # gem 'unicorn'                # Use Capistrano for deployment              # gem 'capistrano-rails', group: :development                gem 'capistrano', '~> 3.1.0'              gem 'capistrano-bundler', '~> 1.1.2'              gem 'capistrano-rails', '~> 1.1.1'              gem 'capistrano-rvm', github: "capistrano/rvm"              # Add this if you're using rbenv              # gem 'capistrano-rbenv', github: "capistrano/rbenv"                    group :development, :test do                # Call 'byebug' anywhere in the code to stop execution and get a debugger console                gem 'byebug'              end                group :development do                # Access an IRB console on exception pages or by using <%= console %> in views                gem 'web-console', '~> 2.0'                  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring                gem 'spring'              end  

Display day of week based on int stored in database

Posted: 08 Jun 2016 05:45 AM PDT

i have a list trading hours stored in my database, and have elected to use int for the weekdays. i am now trying to loop through the code to be able to display a form that will allow the user to update the trading hours for a given day though i am having trouble getting the int for day of the week to be displayed as a string

= form.fields_for :trading_hours do |hours_fields|    %li.mdl-list__item.mdl-list__item--two-line      %span.mdl-list__item-primary-content        = hours_fields.label= Date::DAYNAMES[hours_fields.weekday]        %span.mdl-list__item-sub-title          = hours_fields.time_select :open_time, {:default => {:hour => '9', :minute => '00'}, :minute_step => 15, :ampm => true}          \-          = hours_fields.time_select :close_time, {:default => {:hour => '17', :minute => '00'}, :minute_step => 15, :ampm => true}      %span.mdl-list__item-secondary-action        %label.mdl-checkbox.mdl-js-checkbox.mdl-js-ripple-effect{:for => hours_fields}          = hours_fields.check_box :trades, :class => 'mdl-checkbox__input', :id => hours_fields  

Prerendering React Components With React Rails

Posted: 08 Jun 2016 05:18 AM PDT

I have a simple React component that is currently rendering correctly on the client. I am trying to have it render on the server. To test this I am switching off the JavaScript in Chrome and loading the page.

My component looks like this:

window.TestComponent = React.createClass({    render: function() {        return React.DOM.h1({className: 'TestComponent'},          'Test Component')    }  });  

The entrypoint looks like this:

<%= react_component 'TestComponent', {prerender: true} %>  

At the moment, the page loads without error and contains the following:

<div data-react-class="TestComponent" data-react-props="{'prerender': true}"></div>  

It seems that Rails is parsing the erb, but fails to render the component it references.

I have included The Ruby Racer in my Gemfile and have verified it is working by printing out some calculations to the DOM.

According to the React Rails docs on server-side rendering there are three requirements:

Requirement 1

react-rails must load your code. By convention, it uses components.js, which was created by the install task. This file must include your components and their dependencies (eg, Underscore.js).

My component is located in: app/assets/javascripts/components/test_component.js.erb and should be loaded by the JavaScript in components.js:

//= require_tree ./components  

Requirement 2

Your components must be accessible in the global scope. If you are using .js.jsx.coffee files then the wrapper function needs to be taken into account:

I am using plain JavaScript

Requirement 3

Your code can't reference document. Prerender processes don't have access to document, so jQuery and some other libs won't work in this environment :(

I don't reference document.

What might I be doing wrong?

Rails add captcha code

Posted: 08 Jun 2016 05:13 AM PDT

I am facing some problem regarding adding captcha code .I am reading simple captcha gem which seems quite easy.I am trying to implement in my rails application my problem is I have to implement in my login page.And I have only a session controller I cannot make session model .This is the tutorial which I am following link.So can any tell me how to pass strong params

How to save ids to users columns

Posted: 08 Jun 2016 05:46 AM PDT

So I've built a system of products and a shopping cart in my rails app. The goal I have is to add ids of the saved products from a cart to the user model. So in my cart view page there is a list of all added products in a cart and I want to add a save button which will save those products by their ids to the columns in users table. As an example, if current_user ads three products in the cart with ids 1,2,3 and clicks on "Save" button in a cart, I want to be able to save those three ids by integers to the three columns: product_one, product_two, product_three of the current_user.

So far these are my models:

class Item < ActiveRecord::Base      has_one :cart  end    class User < ActiveRecord::Base      has_one :cart    has_many :items, through: :cart   end    class Cart < ActiveRecord::Base      belongs_to :user    belongs_to :item      validates_uniqueness_of :user, scope: :item  end  

My controllers:

class ItemsController < ApplicationController    before_action :set_item, only: [:show, :edit, :update, :destroy]      respond_to :html, :json, :js      def index      @items = Item.where(availability: true)    end       def show    end       def new       @item = Item.new    end       def edit    end       def create      @item = Item.new(item_params)      @item.save      respond_with(@item)    end       def update      @item.update(item_params)      flash[:notice] = 'Item was successfully updated.'      respond_with(@item)    end       def destroy      @item.destroy      redirect_to items_url, notice: 'Item was successfully destroyed.'    end       private      def set_item        @item = Item.find(params[:id])      end         def item_params        params.require(:item).permit(:name, :description, :availability)       end   end  

my cart controller:

class CartController < ApplicationController      before_action :authenticate_user!, except: [:index]        def add      id = params[:id]      if session[:cart] then        cart = session[:cart]      else        session[:cart] = {}        cart = session[:cart]      end      if cart[id] then        cart[id] = cart[id] + 1      else        cart[id] = 1      end    redirect_to :action => :index    end        def clearCart      session[:cart] = nil      redirect_to :action => :index    end                def index      if session[:cart] then        @cart = session[:cart]      else        @cart = {}      end      end  end  

And I'm using Devise for authentication..

can enable/disable devise lockable module based on condition

Posted: 08 Jun 2016 05:21 AM PDT

I would like to disable/enable devise lockable module for users based on specific condition. For example enable lockable module only for non-admin users.

There was an method in Confirmable module, confirmation_required? which can be overwrite if confirmation is required or not.

http://www.rubydoc.info/github/plataformatec/devise/Devise/Models/Confirmable#confirmation_required%3F-instance_method

Lockable module does have similar method?. any help would be appreciated

Thanks

Rails unkown attribute

Posted: 08 Jun 2016 05:21 AM PDT

I got an error in My rails application

enter image description here

Code looks like this:

oders_controller.rb

 def payMovie      @order = OrderMovie.new      @user = User.find(session[:user_id])      @order.user = @user      @movie = Movie.find params[:id]        puts "sssssssssssss"      puts @movie.inspect        @order.price = @movie.movieprice      @order.currency = @movie.currency      @order.movie << @movie      if @order.save        flash[:notice] = t("flash.saved")        redirect_to :back      else        redirect_to :back      end    end  

models/user.rb

class User < ActiveRecord::Base    has_many :comment    has_and_belongs_to_many :knowledgeprovider    has_and_belongs_to_many :channel    belongs_to :oder_movie  

models/order_movie.rb

class OrderMovie < ActiveRecord::Base    has_one :user    has_one :movie  end  

What could be the problem?

Thanks for your help

UPDATE

@order.inspect  <OrderMovie id: nil, price: nil, currency: nil, user_id: nil, created_at: nil, updated_at: nil, movie_id: nil>    @user.inspect  <User id: 3, firstname: "Felix", lastname: "Hohlweglersad"  

enter image description here

simple_form params hash including blank member?

Posted: 08 Jun 2016 04:57 AM PDT

Why is simple_form always generating a extra blank parameter? This is my code:

<%= f.association :paragraph_titles, as: :check_boxes %>

The params hash returns the checked title_id's PLUS an extra empty member:

"paragraph_title_ids"=>["1","3","5","6",""],

Where does that empty "" come from? How can I avoid it? It also happens if I check all possible titles? thnx in advance ...

Ruby on Rails - use a helper in html.erb

Posted: 08 Jun 2016 04:45 AM PDT

I have a html.erb file used for an email template. Is there any way to include a helper module and use it's methods within this file? Something like:

a mails_helper.rb file:

module MailsHelper    def mail_to      "foo"    end  end  

and in mail_template.html.erb:

<% include MailsHelper %>    <h2> This mail was sent to: <%= mail_to %> </h2>  

When I Search with Twitter Gem Remaining Rate Limit Is Decremented Twice

Posted: 08 Jun 2016 05:24 AM PDT

I am looking for a way to check Twitter API rate limits before of making my consults but for the next snippet every time I call search , remaining is decremented twice instead of just once.

user = User.find_by_id(ID)  client = Twitter::REST::Client.new do |config|    config.consumer_key = CONSUMER_KEY    config.consumer_secret = CONSUMER_SECRECT    config.access_token = user.access_token    config.access_token_secret = user.access_token_secret  end    client.search("baeza")  puts Twitter::REST::Request.new(client, :get, 'https://api.twitter.com/1.1/application/rate_limit_status.json', resources: "search").perform  client.search("baeza")  puts Twitter::REST::Request.new(client, :get, 'https://api.twitter.com/1.1/application/rate_limit_status.json', resources: "search").perform  

I am getting the next result:

{:rate_limit_context=>{:access_token=>"access_token"}, :resources=>{:search=>{:"/search/tweets"=>{:limit=>180, :remaining=>178, :reset=>1465385167}}}}  {:rate_limit_context=>{:access_token=>"access_token"}, :resources=>{:search=>{:"/search/tweets"=>{:limit=>180, :remaining=>176, :reset=>1465385167}}}}  

I would appreciate hearing your thoughts. Thanks for reading!

Dynamic attributes fields creation in form

Posted: 08 Jun 2016 04:27 AM PDT

 I have used producttype and productfield model in my application  #[this][1] is my new.html.erb page  <%= form_for @producttype do | f | %>  <tr>  <td><%= f.label :name%></td>  <td><%= f.text_field :name%></td>  </tr>  <%= f.fields_for :fields do |builder| %>  <%= render 'field_fields', f: builder %>  <% end %>  <%= link_to_add_fields "Add Field", f, :fields %>  <tr>  <td><%= f.submit "Register"%></td>    #this is my coffe script file  $(document).on 'click', 'form .remove_fields', (event) ->  $(this).prev('input[type=hidden]').val('1')  $(this).closest('fieldset').hide()  event.preventDefault()    $(document).on 'click', 'form .add_fields', (event) ->  time = new Date().getTime()  regexp = new RegExp($(this).data('id'), 'g')  $(this).before($(this).data('fields').replace(regexp, time))  event.preventDefault()  

#this is my field_field page <%= f.select :field_type, %w[text_field check_box] %> <%= f.text_field :name ,placeholder: "field name" %> <%= f.check_box :required %> <%= f.label :required %> <%= f.hidden_field :_destroy %> <%= link_to "[remove]", '#', class: "remove_fields" %>

How to get date of particular week in Rails

Posted: 08 Jun 2016 04:25 AM PDT

I am working on Rails application where I am trying to fetch date of particular week but week start from not 1 January of year but some fixed date.

Like, my week start from 8 july 2016 (08-07-2016) so now i want to fetch start date and end date of any week.

Means week 1 start date -> 08-07-2016 and end date -> 14-07-2016.  

Now i want to fetch any week start date and end date but how? I already tried but got solution of year start date not like this.

Any one have idea?

Thanks in advance.

Devise 'Unpermitted parameter: email'

Posted: 08 Jun 2016 04:42 AM PDT

I'm using devise with cancancan and rails_admin. On signing in the admin model, I get the following error.

Unpermitted parameter: email

admin model was generated by devise using rails g devise Admin

I tried overriding the controller and here's my admin/registrations_conroller.rb

class Admin::RegistrationsController < Devise::RegistrationsController        before_action :configure_devise_permitted_parameters, if: :devise_controller?          protected          def configure_permitted_parameters          devise_parameter_sanitizer.for(:account_update).push(:email)          if params[:action] == 'update'            devise_parameter_sanitizer.permit(:account_update) {               |u| u.permit(registration_params << :current_password)            }          elsif params[:action] == 'create'            devise_parameter_sanitizer.permit(:sign_up) {               |u| u.permit(registration_params)             }          end        end        # def new        #   super        # end          # def create        #   super        # end      end  

Here's my admin model

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

My ability.rb

class Ability    include CanCan::Ability      def initialize(admin)      admin ||= Admin.new # guest user (not logged in)      if admin.position? :superadmin          can :manage, :all      else          can :read      end     end  end  

My config/initializers/rails_admin.rb

RailsAdmin.config do |config|      ## == Devise ==     config.authenticate_with do       warden.authenticate! scope: :admin     end     config.current_user_method(&:current_admin)      ## == Cancan ==    config.authorize_with :cancan    config.actions do      dashboard                     # mandatory      index                         # mandatory      new      export      bulk_delete      show      edit      delete      show_in_app        ## With an audit adapter, you can add:      # history_index      # history_show    end  end  

And finally my admins table

create_table "admins", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.string   "position"  end  

What I'm trying to do is have a position column in the admins table which specifies the type of admin i.e. superadmin, moderator etc.

rails + MySQL on OSX(Yosemite)

Posted: 08 Jun 2016 04:02 AM PDT

I was running an old rails project on ruby-1.9.3-p125 until i updated mysql. I ended up removing & reinstalling mysql via homebrew in order to fix issues. I managed to recover the enviroments of all my php projects but not this one.

running ps aux | grep mysql returns:

myuser           19131   0,0  0,1  3570856   6428   ??  S     1:30μμ   0:11.46 /usr/local/Cellar/mysql/5.7.11/bin/mysqld --basedir=/usr/local/Cellar/mysql/5.7.11 --datadir=/usr/local/var/mysql --plugin-dir=/usr/local/Cellar/mysql/5.7.11/lib/plugin --bind-address=127.0.0.1 --log-error=/usr/local/var/mysql/Macbook.local.err --pid-file=/usr/local/var/mysql/Macbook.local.pid  myuser           19039   0,0  0,0  2447704    480   ??  S     1:30μμ   0:00.02 /bin/sh /usr/local/opt/mysql/bin/mysqld_safe --bind-address=127.0.0.1 --datadir=/usr/local/var/mysql  myuser           27974   0,0  0,0  2423356    208 s001  R+    1:22μμ   0:00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn mysql  

When i try to run rake db:create i get the following error:

rake aborted!  uninitialized constant Mysql2::Client::SECURE_CONNECTION  

mysql.server status seems to be running.. when i try to stop (mysql.server stop) i get:

Shutting down MySQL  .. ERROR! The server quit without updating PID file (/usr/local/var/mysql/macbook.local.pid).  

And mysql continue to run but with a new pid id .

Any idea whats wrong with the rails project and how to approach it?

Thanks, C

Need to genrate bills for all users in rails, what should be create method?

Posted: 08 Jun 2016 04:11 AM PDT

Hi,

I need to generate bills for all users (residents) in my app, the bill_controller's create method looks like :

    def create      resident = Resident.find_by(hostel:current_admin_user.hostel) # current_admin_user  action is provided by Activeadmin to access current activeadmin user details         @bill=resident.bills.create(bill_params)        if @bill.save          flash[:info] = "Bills Generated  successfully"          redirect_to new_bill_path        else          flash[:danger] = "Bills Not generated, Please try again!"          redirect_to new_bill_path          end    end  

The active admin users can generate bills, and bills will be generated only for residents that have same hostel with admin user ! And bills should be generated for all residents with specific hostel. check out my code, right now it is generating only for current user(resident logged in) . thanks !

Select tag doesn't display on my form

Posted: 08 Jun 2016 03:42 AM PDT

I'm writing a really simple form with 2 text fields and one select. For some reason, the select tag with options doesn't display on my page. I can see the 2 text fields and the label for the the select, but not the select it self. The app is written in rails and I use materialize.

There might be something too obvious that I don't see it, but after 30mn of thinking, I guess it's fair to put it on SO :) Thanks

Here's the code:

<form action="/resources" method="post">      <input    type="hidden"    name="authenticity_token"    value="<%= form_authenticity_token %>">      <label for="ressource_name">Ressource Name</label>    <input type="text" id="ressource_name" name="resource[ress_name]" value="<%= @resource.ress_name %>">      <label for="ressource_link">Ressource Link</label>    <input type="text" id="ressource_link" name="resource[link]" value="<%= @resource.link %>">        <label for="categories">Categories</label>    <select id="categories" name="resource[category_id]">      <option value="1">Stuff 1</option>      <option value="2">Stuff 2</option>      <option value="3">Stuff 3</option>      <option value="4">Stuff 4</option>      <option value="5">Stuff 5</option>      <option value="6">Stuff 6</option>      <option value="7">Stuff 7</option>      <option value="8">Stuff 8</option>    </select>    <br>    <input type="submit" value="Post">  </form>  

ruby on rails Wildcard how to remove the point from search

Posted: 08 Jun 2016 04:30 AM PDT

I want to use the wildcard search it's working but the problem when i submit more then one it adds each time a point in the input search and it changes result for example

  1. first time when i click in submit cloth.*

  2. second time when i click in submit cloth..*

  3. third time when i click in submit cloth...*

I use this to search_params.query.sub!("",".") because when i use wildcard i should put .* Thanks for help.

Ammend changes to previous Capistrano 3 release

Posted: 08 Jun 2016 03:24 AM PDT

Hello Ruby and web programmers!

In the company where I work, we are currently developing a web application with Ruby on Rails. For production deployments, we use Capistrano 3.

The production deploys will be performed like this:

1. The desired features are implemented.  2. Those features are tested in a test environment (staging).  3. When and all features have been refined and approved,      they are deployed to production (basically with `cap production deploy`).  

The Deploys are performed every 1 or 2 weeks. Thus, suppose that in one month, the following releases are generated:

1. Release nº1 (deploy, week 1)  2. Release nº2 (deploy, week 2)  3. Release nº3 (deploy, week 4)  

Now if in week No. 3 we'd found a critical bug, the release history will look like this:

1. Release nº1 (deploy, week 1)  2. Release nº2 (deploy, week 2)  3. Release nº3 (hotfix, week 3)  4. Release nº4 (deploy, week 4)  

My question is: is there any way to ammend or patch changes to the previous version (in this case, *Release No 2*without rollback? We've taken a look at capistrano-patch, but it seems too complex for what we look for solution.

Thanks in advance!

bundle install gemspec error spree_social.gemspec

Posted: 08 Jun 2016 05:13 AM PDT

In my app when I am running bundle install, I am getting below error.

vendor/gems/spree_social/spree_social.gemspec is not valid. Please fix this gemspec. The validation error was 'spree_social-3.1.0.beta contains itself (spree_social-3.1.0.beta.gem), check your files list'

I tried everything like removing the Gemlock and updating the gems. It didn't work.

Below is my Gemfile

  source 'https://rubygems.org'       ruby '2.3.0'     # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'     gem 'rails', '4.2.5'     # Use sqlite3 as the database for Active Record     gem 'font-awesome-sass', '~> 4.5.0'     # Use SCSS for stylesheets     gem 'sass-rails', '~> 5.0'     # Use Uglifier as compressor for JavaScript assets     gem 'uglifier', '>= 1.3.0'     # Use CoffeeScript for .coffee assets and views     gem 'coffee-rails', '~> 4.1.0'     # See https://github.com/rails/execjs#readme for more supported runtimes     # gem 'therubyracer', platforms: :ruby     gem 'roo-xls'     # Use jquery as the JavaScript library     gem 'jquery-rails'     # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks     gem 'turbolinks'     # Build JSON APIs with ease. Read more:         https://github.com/rails/jbuilder     gem 'jbuilder', '~> 2.0'     # bundle exec rake doc:rails generates the API under doc/api.     gem 'sdoc', '~> 0.4.0', group: :doc     gem 'aws-sdk', '< 2.0'     # Use ActiveModel has_secure_password     # gem 'bcrypt', '~> 3.1.7'     gem 'paperclip'     # Use Unicorn as the app server     # gem 'unicorn'     gem 'rails_12factor', group: :production     # Use Capistrano for deployment     # gem 'capistrano-rails', group: :development       group :development, :test do     # Call 'byebug' anywhere in the code to stop execution and get a  debugger console     gem 'byebug'     gem 'sqlite3'     end      group :production do    # Call 'byebug' anywhere in the code to stop execution and get a  debugger console    gem 'pg'   end      group :development do    # Access an IRB console on exception pages or by using <%= console %> in views     gem 'web-console', '~> 2.0'     gem 'spree_scaffold', github: 'freego/spree_scaffold'     # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'  end        gem 'spree', '3.0.5'    gem 'spree_gateway', github: 'spree/spree_gateway', branch: '3-0-stable'    gem 'spree_wishlist' , :path => File.join(File.dirname(__FILE__), '/vendor/gems/spree_wishlist-2.2.0')   gem 'spree_social',  :path => File.join(File.dirname(__FILE__), '/vendor/gems/spree_social')   gem 'spree_gift_card',  :path => File.join(File.dirname(__FILE__), '/vendor/gems/spree_gift_card')    gem 'stringex'    gem 'spree_reviews',  :path => File.join(File.dirname(__FILE__), '/vendor/gems/spree_reviews')    gem 'spree_auth_devise',  :path => File.join(File.dirname(__FILE__), '/vendor/gems/spree_auth_devise-3.0.6')    gem 'spree_mail_settings',  :path => File.join(File.dirname(__FILE__), '/vendor/gems/spree_mail_settings')    gem 'spree_mail_settings', github: 'spree-contrib/spree_mail_settings', branch: 'master'  

Anyone else faced this?

Thanks

Insert data into a JSONB Column using rails

Posted: 08 Jun 2016 04:46 AM PDT

I have an rails application where I have scaffolded out an entire resource. Now through the UI I am trying to create an record but somehow i have an column in my database which is of type JSONB (Supported by PostGreSQL) whose value is not getting pushed into my table. Can anybody help me out on this as i am relatively new to rails.

Rails app in docker container doesn't reload in development

Posted: 08 Jun 2016 06:21 AM PDT

I followed the docker-compose tutotial on howto start a rails app. All run perfectively but the app isn't reloaded when I change a controller.

What can it be missing?

Credit card number is stored as a plain text while using Activemerchant gem with paypal integration

Posted: 08 Jun 2016 02:58 AM PDT

I am working on a maintenance project which is in Rails 3.2.3. Here for payments they are using Active Merchant gem for Paypal integration. As per the code review I did, mostly the code is written based on this railscast.

When I enter a credit card number, it is saved as a plain text. Does Active Merchant have any mechanism to encrypt this card number? or Is there any way to store this card number as either "xxxx-xxx-xxx-xxxx" or encrypted?

No comments:

Post a Comment