Wednesday, June 22, 2016

Ruby on Rails query: find all entity that contains fixed strings | Fixed issues

Ruby on Rails query: find all entity that contains fixed strings | Fixed issues


Ruby on Rails query: find all entity that contains fixed strings

Posted: 22 Jun 2016 08:07 AM PDT

I have the following Ruby on Rails entity:

Playlist:

class Playlist < ActiveRecord::Base {                               :id => :integer,                             :name => :string,                       :created_at => :datetime,                       :updated_at => :datetime,                        :dimension => :string,                            :title => :string,                             :text => :string,                            :price => :float,         :playlist_image_file_name => :string,      :playlist_image_content_type => :string,         :playlist_image_file_size => :integer,        :playlist_image_updated_at => :datetime,                             :main => :boolean,                           :action => :string,                   :hairdresser_id => :integer  }  

And Keyword:

class Keyword < ActiveRecord::Base {               :id => :integer,             :name => :string,       :created_at => :datetime,       :updated_at => :datetime,      :preselected => :boolean  }  

The relation between them is very simple: basically a Playlist object can have 0 or more keywords associated. Those are the models:

class Keyword < ActiveRecord::Base    has_and_belongs_to_many :playlists  end    class Playlist < ActiveRecord::Base    has_and_belongs_to_many :keywords      has_attached_file :playlist_image, styles: {medium: "500x500", small: "200x200", thumb: "40x40"}, default_url: "/system/playlist_default.jpg"    validates_attachment_content_type :playlist_image, content_type: /\Aimage\/.*\Z/  end  

That allows me to do something like that:

Playlist.first.keywords  

and retrieve all the keywords associated with the first playlist.

Now I would like to build a function to return all the playlists that have certain words as keywords and have "main" equals to true. For example all the playlist that have the keyword "Summer". I tryed with that:

Playlist.where(:main => true).map{|x| x.keywords.include? "Summer"}  

But that returns only an array containing true or false depending if the related Playlist contains or not the keyword "Summer", I'm looking for something that return the whole playlist only if the array of keywords of that playlist include the word "summer". How can I achieve that?

Using both has_one and has_many association

Posted: 22 Jun 2016 08:03 AM PDT

I'm trying to the has_one and has_many methods in one model. A taskflow can have many tasks but it also has a single default task.

I'm trying to create a column in the taskflow table that contains the id of a task. However when I try and set that default task it does not work.

class Taskflow < ActiveRecord::Base      has_many :tasks      has_one :default_task, :class_name => 'Task'    class Task < ActiveRecord::Base      belongs_to :taskflow  

I seed the database then in the rails console I try to assign a task to be a taskflow default_task:

taskflow1 = Taskflow.first  task1 = Task.first  taskflow1.default_task = task  

This doesn't work with the taskflow default_task value remaining 'nil'. What the correct way to achieve the desired behaviour?

Any help would be much appreciated.

Shorthand block syntax for factory_girl traits

Posted: 22 Jun 2016 08:00 AM PDT

Is it possible to use the shorthand block syntax for factory_girl traits?

Consider this factory:

FactoryGirl.define do    factory :foo do      name "name"        # not using the block shorthand {} syntax, instead using do...end block syntax      trait :my_name do        name "Neil"      end      end  end  

And using this factory works:

create(:foo, traits: [:my_name])  

However I would like to use the shorthand block syntax for my traits like so:

FactoryGirl.define do    factory :foo do      name "name"        # using shorthand block syntax but does not work      trait :my_name {name "Neil"}      end  end  

And now using this factory errors out. Here is what happens:

create(:foo, traits: [:my_name])  

syntax error, unexpected '{', expecting keyword_end (SyntaxError)

This seems odd because I thought that wherever you use do ... end you can opt for the shorthand {} block syntax.

Question: Is there something wrong with my shorthand block syntax for the factory_girl trait method and that is why it is erroring out? Or: are you just not allowed to use the shorthand block syntax with factory_girl traits? Is there a way to make using the shorthand block syntax for factory_girl traits work?

Docs on the factory_girl trait attribute

Access count of message received?

Posted: 22 Jun 2016 07:48 AM PDT

Is it possible to access in a test how many times an object has received a certain message? My goal is to test that a class has received two class method calls the same number of times.

Logically, it seems like this count would be stored somewhere as code is executed.

This would look something like

allow(SomeClass).to receive(:method_1).at_least(1).times  allow(SomeClass).to receive(:method_2).at_least(1).times    # setup and code here    expect(method_1_received_times).to eq (method_2_received_times)  

Alternative to setInterval

Posted: 22 Jun 2016 07:44 AM PDT

I'm working on a website in which notifications and comments are reloaded every 3 seconds. I implemented this using setInterval--as Facebook's React Tutorial suggested--but I quickly realized that this may be inefficient.

I'm currently using Ruby on Rails and React. What are the alternatives?

Double everything in my db logs Rails

Posted: 22 Jun 2016 07:43 AM PDT

I have double everything in my logs. Not sure how to get rid of it. Any suggestions?

  Bid Load (0.2ms)  SELECT "bids".* FROM "bids" WHERE "bids"."order_id" = $1  [["order_id", 7]]    Bid Load (0.2ms)  SELECT "bids".* FROM "bids" WHERE "bids"."order_id" = $1  [["order_id", 7]]    Size Load (0.2ms)  SELECT  "sizes".* FROM "sizes" WHERE "sizes"."order_id" = $1 LIMIT 1  [["order_id", 7]]    Size Load (0.2ms)  SELECT  "sizes".* FROM "sizes" WHERE "sizes"."order_id" = $1 LIMIT 1  [["order_id", 7]]    Bid Load (0.2ms)  SELECT "bids".* FROM "bids" WHERE "bids"."order_id" = $1  [["order_id", 8]]    Bid Load (0.2ms)  SELECT "bids".* FROM "bids" WHERE "bids"."order_id" = $1  [["order_id", 8]]    Size Load (0.3ms)  SELECT  "sizes".* FROM "sizes" WHERE "sizes"."order_id" = $1 LIMIT 1  [["order_id", 8]]    Size Load (0.3ms)  SELECT  "sizes".* FROM "sizes" WHERE "sizes"."order_id" = $1 LIMIT 1  [["order_id", 8]]    Bid Load (0.2ms)  SELECT "bids".* FROM "bids" WHERE "bids"."order_id" = $1  [["order_id", 9]]    Bid Load (0.2ms)  SELECT "bids".* FROM "bids" WHERE "bids"."order_id" = $1  [["order_id", 9]]    Size Load (0.2ms)  SELECT  "sizes".* FROM "sizes" WHERE "sizes"."order_id" = $1 LIMIT 1  [["order_id", 9]]    Size Load (0.2ms)  SELECT  "sizes".* FROM "sizes" WHERE "sizes"."order_id" = $1 LIMIT 1  [["order_id", 9]]    Bid Load (0.2ms)  SELECT "bids".* FROM "bids" WHERE "bids"."order_id" = $1  [["order_id", 10]]    Bid Load (0.2ms)  SELECT "bids".* FROM "bids" WHERE "bids"."order_id" = $1  [["order_id", 10]]    CACHE (0.0ms)  SELECT  "printers".* FROM "printers" WHERE "printers"."id" = $1 LIMIT 1  [["id", 1]]    CACHE (0.0ms)  SELECT  "printers".* FROM "printers" WHERE "printers"."id" = $1 LIMIT 1  [["id", 1]]    Size Load (0.2ms)  SELECT  "sizes".* FROM "sizes" WHERE "sizes"."order_id" = $1 LIMIT 1  [["order_id", 10]]    Size Load (0.2ms)  SELECT  "sizes".* FROM "sizes" WHERE "sizes"."order_id" = $1 LIMIT 1  [["order_id", 10]]  

Rails Version Rails 4.2.5 Ruby Version 2.3.0

ActiveRecord::Base#assign_attributes monkey patch doesn't work after Rails 4 upgrade

Posted: 22 Jun 2016 07:32 AM PDT

I'm upgrading an existing Rails 3 upgrade to Rails 4. This application monkey patches ActiveRecord::Base#assign_attributes and was working fine in Rails 3; now in Rails 4 the monkey patched code never gets called.

I have a config initializer which requires the monkey patched code from the lib directory and I can see that it is run once during the startup initialization process.

This is a simplified version of the monkey patch file from the lib directory.

# encoding: UTF-8  module ActiveRecord    class Base      alias_method :default_assign_attributes, :assign_attributes        def assign_attributes(new_attributes)        # Do some custom stuff here        default_assign_attributes(new_attributes)      end      end  end  

nested_form and has_many association in Rails

Posted: 22 Jun 2016 07:23 AM PDT

I have two models called Consumer and Complaint as follows:

class Complaint < ActiveRecord::Base    belongs_to :consumer  end      class Consumer < ActiveRecord::Base    has_many :complaints      accepts_nested_attributes_for :complaints  end  

Using nested_form I can register a Consumer and a Complaint at the same time, but I perform a search before to verify wheter a consumer is already registered.

If it's true, the form loads data from Consumer and loads data from all Complaints previous registered for this Consumer.

I want to load data only from Consumer and have blank fields for just one Complaint, and when submitting the form, update the Consumer, if needed, and save the new Complaint (as though the association was has_one).

I'm not fluent in English so I apologize for any mistake.

Getting "FATAL: role "root" does not exist" when trying to do "docker up"

Posted: 22 Jun 2016 07:31 AM PDT

I'm starting to work with an existing Rails project that uses Docker. I've used Rails for a long time but never Docker.

After I do a docker build . I try to do a docker-compose up, but I get:

FATAL: role "root" does not exist /usr/local/bundle/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/postgresql_adapter.rb:661:in `rescue in connect': FATAL: role "root" does not exist (ActiveRecord::NoDatabaseError)

It seems to me that the Docker machine is probably trying to connect to the database as the root user, but there's no role called root, so the connection is rightly failing.

The thing I don't know is why Docker is apparently trying to connect to the database as root and how to get it to use the right user.

Here's my database.yml:

development:    database: my_app_development    adapter: postgresql    encoding: unicode    pool: 5  

Any help is appreciated.

Edit: here's my docker-compose.yml:

web:    build: .    volumes:      - .:/my_app    ports:      - "3000:3000"    links:      - postgres      - redis      - mailcatcher    env_file:      - 'config/application.yml'  postgres:    image: postgres:9.4    ports:      - "5432"    env_file:      - 'config/database.yml'  redis:    image: redis:3.0.6  mailcatcher:    image: schickling/mailcatcher    ports:      - "1080:1080"  

How to successfuly use validate_token in the devise_token_auth gem?

Posted: 22 Jun 2016 07:25 AM PDT

I am fairly new to Ruby and Rails itself and I'm trying to build a simple Rails API.

I want to authenticate users via token and I am therefore using the devise_token_auth gem.

I can successfuly make a POST request at /auth/sign_in and I am now trying to make a GET request at /auth/validate_token

What I have, as a "test":

    uri = URI.parse("http://localhost:3000/auth/sign_in")      response = Net::HTTP.post_form(uri, {"email" => params[:session][:email], "password" => params[:session][:password]})        uri2 = URI.parse("http://localhost:3000/auth/validate_token")      params = { :auth_token => response['access-token'], :uid => response['uid'], :client => response['client'] }      uri2.query = URI.encode_www_form(params)      response2 = Net::HTTP.get_response(uri2)  

I am therefore using the access-token and uid retrieved from the response header but I keep getting a 401 response code from /auth/validate_token:

 Started GET "/auth/validate_token?auth_token=EEV40VDHfOaWtBzv3bn_DQ&uid=username%40example.com&client=NAzWNJalYBJLRni9dCGxXA" for ::1 at 2016-06-22 15:22:35 +0100   Processing by DeviseTokenAuth::TokenValidationsController#validate_token as */*     Parameters: {"auth_token"=>"EEV40VDHfOaWtBzv3bn_DQ", "uid"=>"username@example.com", "client"=>"NAzWNJalYBJLRni9dCGxXA"}   Completed 401 Unauthorized in 0ms (Views: 0.1ms | ActiveRecord: 0.0ms)  

What am I doing wrong? How can I solve this?

assign value to database from braintree api call

Posted: 22 Jun 2016 06:53 AM PDT

I am trying to save the customer id which is being created by braintree to my database. i can see that id is being created on braintree and echoed in my terminal but when attempting to allocate to a column within my database it doesn't appear to be saving

I, [2016-06-22T23:30:13.267296 #8775]  INFO -- : [Braintree] [22/Jun/2016 13:30:13 UTC] POST /merchants/xxxxx/customers 201  86502732      def create_braintree_customer      # self.access_token = SecureRandom::hex(9+rand(6)) if access_token.nil?      result = Braintree::Customer.create(          :first_name => self.first_name,          :last_name => self.last_name,          :email => self.email,          :phone => self.mobile      )      if result.success?        puts result.customer.id        self.customer_cim_id = result.customer.id      else        p result.errors      end    end  

Rails/ruby replace hash value

Posted: 22 Jun 2016 07:19 AM PDT

I have array of hashes and want to replace value

  [{"__content__"=>"Guitars", "id"=>"2"},   {"__content__"=>"For Guitars", "id"=>"3", "parentId"=>"2"},   {"__content__"=>"6-string", "id"=>"24", "parentId"=>"2"},   {"__content__"=>"7-string", "id"=>"25", "parentId"=>"2"},   {"__content__"=>"8-string", "id"=>"26", "parentId"=>"2"}]  

I want to turn it into

Want to replace parentId value with __content__

  [{"__content__"=>"Guitars", "id"=>"2"},   {"__content__"=>"For Guitars", "id"=>"3", "parentId"=>"Guitars"},   {"__content__"=>"6-string", "id"=>"24", "parentId"=>"Guitars"},   {"__content__"=>"7-string", "id"=>"25", "parentId"=>"Guitars"},   {"__content__"=>"8-string", "id"=>"26", "parentId"=>"Guitars"}]  

How can I do it?

Migrating from heroku to dokku (digital ocean)

Posted: 22 Jun 2016 06:22 AM PDT

I'm switching everything from heroku off and moving to digital ocean (cheaper and a static ip address!!)

I have searchbox on heroku. And i'll be needing something like this on digital ocean.

Currently i'm hitting an error making a request (still setup for heroku?) That looks like this

I, [2016-06-22T13:18:41.226034 #275]  INFO -- : Started GET "/events_autocomplete?query=test" for 212.250.145.155 at 2016-06-22 13:18:41 +0000  I, [2016-06-22T13:18:41.253478 #275]  INFO -- : Processing by EventsController#autocomplete as JSON  I, [2016-06-22T13:18:41.253665 #275]  INFO -- :   Parameters: {"query"=>"test"}  I, [2016-06-22T13:18:41.264460 #275]  INFO -- : Completed 500 Internal Server Error in 11ms (Searchkick: 5.7ms | ActiveRecord: 0.0ms)  F, [2016-06-22T13:18:41.266812 #275] FATAL -- :  Faraday::ConnectionFailed (Connection refused - connect(2) for "localhost" port 9200):    app/controllers/events_controller.rb:61:in `autocomplete'      I, [2016-06-22T13:18:41.319310 #275]  INFO -- : Started GET "/search_events?utf8=%E2%9C%93&search=test&commit=Search" for 212.250.145.155 at 2016-06-22 13:18:41 +0000  I, [2016-06-22T13:18:41.321272 #275]  INFO -- : Processing by EventsController#search as HTML  I, [2016-06-22T13:18:41.321365 #275]  INFO -- :   Parameters: {"utf8"=>"✓", "search"=>"test", "commit"=>"Search"}  I, [2016-06-22T13:18:41.326730 #275]  INFO -- : Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.0ms)  F, [2016-06-22T13:18:41.328614 #275] FATAL -- :  Faraday::ConnectionFailed (Connection refused - connect(2) for "localhost" port 9200):    app/controllers/events_controller.rb:83:in `search'  

I'm very new at this so any help would be much appreciated

Thanks Sam

Rails: ActiveRecord custom average calculation

Posted: 22 Jun 2016 06:32 AM PDT

Outside of using a raw SQL query, is there a nice way to divide an active record query by a constant? A variable?

Example:

Phones.group(:year).order(:year).average(:talk_time_min)  

If I wanted to retrieve the talk_time_min in seconds, how could I dotalk_time_min / 60?

Html radio button labels don't select the proper radio button (Ruby on Rails)

Posted: 22 Jun 2016 06:03 AM PDT

(Ruby on Rails application)

I'm having a problem with selecting radio buttons by clicking their designated labels (I have multiple forms on the same page).

In my application, I have a Conversations resource, where in its show page Users can send Messages into the conversation. In 'conversations/show' users can React to each others' messages. I use a ReactionExample model to create a few reaction_examples at a time, which users can select and create their own new instance of Reaction from.

here is the show action in conversations controller

def show     @conversation = Conversation.find(params[:id])     @messages = @conversation.messages.all     @reaction_examples = ReactionExample.all #These are "like", "hate", etc...  end  

here is my 'conversations/show' view

<% @messages.each do |message| %>     <p><%= message.user.first_name %> says <%= message.content %></p>     <%= form_for message.replies.build, url: reaction_conversation_path(@conversation) do |f| %>        <%= f.hidden_field :message_id, value: message.id %>        <%= f.hidden_field :user_id, value: current_user.id %>        <% @reaction_examples.each do |example| %>           <%= f.radio_button :reaction_example_id, example.id %>           <%= f.label :reaction_example_id, example.phrase, value: example.id %>        <% end %>        <%= f.submit "Send reaction" %>     <% end %>  <% end %>  

Here is my problem: in this view ('conversations/show') there will be multiple forms to send a reaction. Each of these forms will have more than one radio button and label with the same value, just a different :message_id on each form. I would like to be able to select a reaction radio button by clicking its label, but there are multiple forms on this page with radio buttons WHICH HAVE THE SAME LABEL VALUE. So when I click a radio button label on the third or fourth message down on the page, it selects the radio button on the first message up on the page. It's because they technically have the same value since the same ReactionExample id's are being used in each radio button in the forms.

Any help is appreciated. Thank you in advance!

Rails associations for organisation with multiple locations

Posted: 22 Jun 2016 08:04 AM PDT

I have the following models: Organisation, Valuation and Capability.

The Organisation model used to have a country field, but it came to my attention it can have multiple locations.

To solve this I could create a Location model and add a has_many relation between Organisation and Location, equally however a location can belong to more than one organisation. For example, Organisation X might have a location in UK, DE and US and organisation Y might have a location in UK and DE.

The bigger problem lies with Valuation which describes valuations of a organisation at a specific location for a specific capability. So where the valuation at organisation X in location Y might be 10, it could be 8 for organisation X at location Z.

Right now Valuation has belongs_to assocations to both Organisation and Capability:

class Valuation < ApplicationRecord    belongs_to :organisation    belongs_to :capability  end  

To account for the location, I would need to add another association, but I am looking for some hints as to which one.

The question then is, how to set up my assocations so I can ask questions like:

"what is the average valuation of organisation x with capability y over all locations"

or

"what is the valuation of organsiation x for capability y at location z"

EDIT

Ended up going with the many-to-many approach, ended up with the models:

class Organisation < ApplicationRecord    has_many :memberships    has_many :locations, through: :memberships  end    class Location < ApplicationRecord        has_many :memberships    has_many :organisations, through: :memberships  end    class Membership < ApplicationRecord    belongs_to :organisation    belongs_to :location  end  

Question now is to link this to Valuation

Rails can't connect to external mysql server despite Privileges

Posted: 22 Jun 2016 07:02 AM PDT

I run rails on my local dev environment but the mysql instance is on a separate server.

When trying to open a page in the app I get this error:

Access denied for user 'username'@'myhostname.lan' (using password: YES)

When I ssh into the server running mysql and run this command SELECT Host from mysql.user WHERE User='username'; I get the following:

+---------------------+  | Host                |  +---------------------+  | %                   |  | myhostname.lan      |  | localhost           |  +---------------------+  

All of these entries were created with GRANT ALL PRIVIELEGES ON dbname.* TO ...

So why can I not connect given that both the any-host wildcard % is in the list as well as the hostname I try to connect from specifically?

Rails authenticate mongodb_logger with devise

Posted: 22 Jun 2016 05:51 AM PDT

I've got installed gems mongodb_logger and devise.
I was wondering how to restrict access to users who are registered in devise ?
I tried as follows( restricting to users with admin role)

authenticate :user, ->(u) { u.admin? } do
mount MongodbLogger::Server.new, at: "/mongodb_logger", as: :mongodb_logger,

in my routes.rb. But this didn't help... How can I do such a thing ?

Why is Descending Ordering not working in Elastic Search

Posted: 22 Jun 2016 05:46 AM PDT

I want to build a query, which gives me all the index content sorted by date with descending order and a date range, but the query gives me only a few entries back.

Querying with Ascending order works without problems.

My query:

query: {      match_all: {}    },    sort: {      bornAt: {        order: 'desc'      }    },    filter: {        range: {            bornAt: {                lte: 'now',                gte: '1800-01-01'              }        }    }  )  

act_as_taggable gem for nested resources

Posted: 22 Jun 2016 05:40 AM PDT

Have a form that uses act_as_taggable, the problem is that script is only working for one single post - the first one one show page.

How would you do this different from how we are trying it? :) if there is something silly here its cause its three beginners working together (we have only been coding for about 3 months).

Script on the page:

   <script>    $(document).on('ready page:load', function () {      $('#item_tag_ids').chosen({        allow_single_deselect: true,        width: '100%'      })    });    </script>  

Inventory:

<div class="row">    <ul class="thumbnails files">      <% unless @items.empty? %>      <% @items.each do |pic| %>      Title:<%= pic.title %><br>      Description:<%= pic.description %>      Tags:<%= raw pic.tag_list.map { |t| link_to t, inventory_tag_path(@inventory.id, t) }.join(', ') %>        <li class="span3" id="item_<%= pic.id %>">        <div class="thumbnail">          <%= image_tag pic.image.url(:medium) %>          <div class="caption">            <p style="text-align: center;">              <% @item = pic %>              <%= render 'items/form' %>              <%=              link_to "Delete item", inventory_item_path(@inventory, pic),              :data => { :confirm => "Are you sure?" },              :method => :delete              %>                        </p>          </div>        </div>      </li>      <% end %>      <% end %>    </ul>  </div>  

Form for item that gets rendered on inventory show:

    <div class="form-inputs">      <%= f.input :title %>      <%= f.input :description %>      <%= f.label :tag_list, 'Tags (separated with comas)' %>      <%= f.collection_select :tag_ids, Tag.order(:name), :id, :name, {}, {multiple: true} %>    </div>      <div class="form-actions">      <%= f.button :submit %>    </div>  

The controller function for inventory show:

  def show      @inventory = Inventory.find(params[:id])        if params[:tag]        @items = @inventory.items.tagged_with(params[:tag])      else        @items = @inventory.items      end          respond_to do |format|        format.html # show.html.erb        format.json { render json: @inventory }      end    end  

Get data in Rails using AJAX every second

Posted: 22 Jun 2016 05:42 AM PDT

Goal: Scan all links on a given website and show real time number of links scanned so far before it will be done. Thanks!

1 - I have a form where a user can post a website and it will scan links:

def create      link = Link.new(set_url_params)      link.save      session[:link_id] = link.id      redirect_to links_result_path  end  

2 - It redirects a user to a method result where is another method scan_links to find all links on the given website and save it to an array @links:

  def result      link = Link.find(session[:link_id])      @data = scan_links(link.url)       end          def scan_links(url)      @links = []      Spidr.site(url) do |spider|        spider.every_url do |url|          @links << url.to_s        end      end    end  

3 - I wrote another method to access the object @links and count it in a real time + respond in json object every second with ajax request.

  def real_time_count_links      respond_to do |format|        format.html        format.json {render json: @links.count}      end    end  

4 - And finally I wrote the ajax request for that method to access it every second:

function openScan() {      document.getElementById("Scan").style.height = "100%";      function doAjax() {       $.ajax({        type: 'get',        url: "/links/real_time_count_links",        dataType: 'json',        success: function(response) {          alert("ok.")        },        complete: function (data) {          // Schedule the next          setTimeout(doAjax, 1000);        }      });    };    setTimeout(doAjax, 1000);  }  

There is something wrong with it, not sure what and I don't think so this is the best way to handle it. How I can access data in ajax in real time till the page / method "result" is fully loaded and shows all the links?

collection-select dropdown method using database in rails 4

Posted: 22 Jun 2016 05:33 AM PDT

I have 3 tables. 1. Library with Library_id, library_name 2. department with dep_id, dep name and lib_id as FK. 3. reference with ref_id, dep_id(FK), lib_id(FK), book_name and book_author. Now i have models in rails corresponding to it. In articles index I want to create collect select query. Can you please give me a sample code for that.

Rails Paperclip - manage assets via utility class

Posted: 22 Jun 2016 05:40 AM PDT

I have to manage user avatars via a utility class in my Rails app. The utility class is already implemented and I can not modify it.

Getting the avatar is done through a call like ThatUtility.get_avatar(user_id), the same for update and delete. ThatUtility stores and retrieves files from another server via REST calls, and there must be no file storing on my local machine.

Is there a way to use Paperclip in my situation?

How do we override ActiveRecord::Migration class?

Posted: 22 Jun 2016 05:33 AM PDT

I just wants to override the base migration class by adding some attribute in it. e.g: for the purpose of soft delete, i wants whenever i generate a new migration using "rails g migration", is_deleted column always be there. So the point is where we can define this is_deleted column as default column, to avoid re-writing it in each migration?

Create 2 types of resources using the same view

Posted: 22 Jun 2016 05:52 AM PDT

I have 2 models (and resources) - Institute and Admin.

I want to have a view with 1 submit button that creates 2 types of resources. Would I need to have 2 separate forms? An example would be great!

Also, what naming convention should this view use (given that it creates 2 types resources).

There is a "has-many through" association between Institute and Admin.

Redmine install process installing rmagick 2.15.4 failed

Posted: 22 Jun 2016 04:27 AM PDT

I am in process of installing Redmine app via RedmineInstall documentation I have to install rmagick via command:

bundle install  

then error see below.

I use redmine 3.3.0 64 for windows

I install ImageMagick 7.0.2 via HowTo but can not install gem. Where can be the problem?

d:\Install\Ruby\Ruby22-x64\bin>bundle install  Fetching gem metadata from https://rubygems.org/  Fetching version metadata from https://rubygems.org/  Fetching dependency metadata from https://rubygems.org/  Using rake 11.2.2  Using i18n 0.7.0  Using json 1.8.3  Using minitest 5.9.0  Using thread_safe 0.3.5  Using builder 3.2.2  Using erubis 2.7.0  Using mini_portile2 2.1.0  Using pkg-config 1.1.7  Using rack 1.6.4  Using mime-types-data 3.2016.0521  Using arel 6.0.3  Using addressable 2.4.0  Using coderay 1.1.1  Using concurrent-ruby 1.0.2  Using htmlentities 4.3.1  Using thor 0.19.1  Using mimemagic 0.3.1  Using mysql2 0.3.21  Using net-ldap 0.12.1  Using ruby-openid 2.3.0  Using bundler 1.12.5  Using rbpdf-font 1.19.0  Using redcarpet 3.3.4  Using request_store 1.0.5  Installing rmagick 2.15.4 with native extensions    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        D:/Install/Ruby/Ruby22-x64/bin/ruby.exe -r ./siteconf20160622-56680-zypeq0.r  b extconf.rb  *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:          --with-opt-dir          --without-opt-dir          --with-opt-include          --without-opt-include=${opt-dir}/include          --with-opt-lib          --without-opt-lib=${opt-dir}/lib          --with-make-prog          --without-make-prog          --srcdir=.          --curdir          --ruby=D:/Install/Ruby/Ruby22-x64/bin/$(RUBY_BASE_NAME)  extconf.rb:110:in ``': No such file or directory - identify -version (Errno::ENO  ENT)          from extconf.rb:110:in `configure_compile_options'          from extconf.rb:16:in `initialize'          from extconf.rb:517:in `new'          from extconf.rb:517:in `<main>'    extconf failed, exit code 1    Gem files will remain installed in D:/Install/Ruby/Ruby22-x64/lib/ruby/gems/2.2.  0/gems/rmagick-2.15.4 for inspection.  Results logged to D:/Install/Ruby/Ruby22-x64/lib/ruby/gems/2.2.0/extensions/x64-  mingw32/2.2.0/rmagick-2.15.4/gem_make.out  Using tzinfo 1.2.2  Using nokogiri 1.6.8  Using rack-test 0.6.3  Using mime-types 3.1  Using css_parser 1.3.7  Using sprockets 3.6.2  Using rack-openid 1.4.2  Using rbpdf 1.19.0  An error occurred while installing rmagick (2.15.4), and Bundler cannot  continue.  Make sure that `gem install rmagick -v '2.15.4'` succeeds before bundling.       :         bundler: command not found: rake      Install missing gem executables with ´bundle install´  

How to login into active admin with two user models

Posted: 22 Jun 2016 04:04 AM PDT

I have 2 different types of users in my rails application. For those 2 types of users, i created two different models. I want to give login access for both models (Webadmin, Owner).

My routes.rb file :

devise_for :webadmins, ActiveAdmin::Devise.config.merge({path: '/webadmin'})  devise_for :owners, ActiveAdmin::Devise.config  ActiveAdmin.routes(self)  

My activeadmin.rb file :

config.load_paths = [File.join(Rails.root,'app','webadmin'), File.join(Rails.root,'app','owner')]  config.default_namespace = :webadmin    config.namespace :webadmin do |webadmin|    webadmin.authentication_method = :authenticate_webadmin!    webadmin.current_user_method = :current_webadmin    webadmin.logout_link_path = :destroy_webadmin_session_path  end    config.namespace :owner do |owner|    owner.authentication_method = :authenticate_owner!    owner.current_user_method = :current_owner    owner.logout_link_path = :destroy_owner_session_path  end  

when i am running my application using rails s, i am getting the following error.

/home/brilliance/.rvm/gems/ruby-2.2.1/gems/devise-3.5.6/lib/devise/rails/routes.rb:499:in `raise_no_devise_method_error!': Webadmin does not respond to 'devise' method. This usually means you haven't loaded your ORM file or it's being loaded too late. To fix it, be sure to require 'devise/orm/YOUR_ORM' inside 'config/initializers/devise.rb' or before your application definition in 'config/application.rb' (RuntimeError)  

I tried a lot of answers from google and stackoverflow. But No luck. Please help me out.

Overriding Devise token auth emails

Posted: 22 Jun 2016 04:02 AM PDT

I have created two models created using devise_token_auth namely admin and user.

During account confirmation and for password reset emails are to be sent for the respective users/admins, but the content in the mails for the users and admins are different.

i have used the following command to generate email views for user model

rails generate devise_token_auth:install_views  

But i need to have another set of views for admin, how can i achieve it.

After adding controller in active admin resource , validations error cannot be shown

Posted: 22 Jun 2016 04:14 AM PDT

Previously i have form and show method in active admin resource. At that time validation errors shown in forms. But now i have to write controller in resource , after adding no more validation errors. Am i doing something wrong. Below is my code.

ActiveAdmin.register PsychographicsQuestion do      config.clear_action_items!    permit_params :id , :title,:psychographics_question_type ,:expiry_date , :_destroy , psychographics_options_attributes: [:id,:title , :_destroy]      form do |f|      f.semantic_errors *f.object.errors.keys      f.inputs "Question" do           f.input :title , label: "Question"        f.input :psychographics_question_type, label: "Question Type" ,:prompt => 'Select Answer Type', :as => :select, :collection => DemographicsQuestion.demographics_question_types.keys.to_a        f.input :expiry_date, as: :datepicker, datepicker_options: { min_date: 0}      end      f.has_many :psychographics_options,heading: 'Options' do |item|        item.input :title       end      f.actions    end      show do      attributes_table do        row :title        row :psychographics_question_type        row :expiry_date      end    end    controller do      def create        question = PsychographicsQuestion.create(permitted_params["psychographics_question"])          if question.id != nil            PsychographicsQuestionFilter.create(@@filters)          filter_user = User.search(@@users)            for u in filter_user.result            FiltersMatching.create(:user_id => u.id, :psychographics_filters_id => @@filters.to_i , :psychographics_question_id => question.id)              #send_msg_through_gcm(u.to_i,"New PsychoGraphics question has been added.")              NotificationsDatum.create(:user_id => u.id , :msg => "New PsychoGraphics question has been added." , :category => NotificationsDatum.categories["PsychographicsQuestion"] , :status=>NotificationsDatum.statuses["Active"] , :viewed_status=>NotificationsDatum.viewed_statuses["NotViewed"] , :psychographics_question_id => question.id)            end              redirect_to admin_psychographics_question_path(:id => 93)          else            redirect_to new_admin_psychographics_question_path(:id => question.id)          end        end      end        filter :expiry_date      filter :created_at    end   

Openstack Ovh connection configuration

Posted: 22 Jun 2016 03:46 AM PDT

I am currently working on a rails app and I want to use Openstack with object storage from OVH.

My error is : connect_nonblock': SSL_connect returned=1 errno=0 state=unknown state: certificate verify failed (OpenSSL::SSL::SSLError) Unable to verify certificate. This may be an issue with the remote host or with Excon.Excon has certificates bundled, but these can be customized.Excon.defaults[:ssl_ca_path] = path_to_certs,ENV['SSL_CERT_DIR'] = path_to_certs,Excon.defaults[:ssl_ca_file] = path_to_file,ENV['SSL_CERT_FILE'] = path_to_file,Excon.defaults[:ssl_verify_callback] = callback(see OpenSSL::SSL::SSLContext#verify_callback), orExcon.defaults[:ssl_verify_peer] = false` (less secure). (Excon::Errors::CertificateError)

Does anyone have a tips to do it ?

I have followed this tutorial in french: https://gist.github.com/BaptisteDixneuf/85dc4419a0398446d2d3

and there is my carrierwave config file :

CarrierWave.configure do |config|   config.fog_provider = 'fog/openstack'   config.fog_credentials = {      :provider              => 'OpenStack',      :openstack_username    => ENV['OS_USERNAME'],      :openstack_api_key => ENV['OS_USER_MDP'],      :openstack_auth_url => ENV['OS_AUTH_URL'],      :openstack_region    => 'GRA1'    }    end  

No comments:

Post a Comment