Wednesday, July 6, 2016

How can I use order and find_each in neo4j.rb, Rails? | Fixed issues

How can I use order and find_each in neo4j.rb, Rails? | Fixed issues


How can I use order and find_each in neo4j.rb, Rails?

Posted: 06 Jul 2016 07:36 AM PDT

I use Neo4j.rb in Rails. I am trying this code.

 Person.all.order("n.score").find_each  

or

Person.order(score: :asc).find_each  

But,its does not get person order by.

What's the proper way to check if JSON has a key?

Posted: 06 Jul 2016 07:37 AM PDT

I'm using Rails 4.2.3. I have this code that is supposed to parse JSON

my_object_id = my_object.key?("id") ? my_object['id'] : nil  

But when the "my_object" JSON is '["name", "Info"]', I get the below error

undefined method `key?' for ["name", "Info"]:Array  

What's the proper way check if my JSON is going to have an "id" key?

Implement rails ajax search in rails 4.2.0

Posted: 06 Jul 2016 07:30 AM PDT

I would like to implement ajax search to my rails application.So how do I proceed with my defined code.

I want to search with respect to the description, paid amount etc.

For better understanding follow the image;

screenshot.png

index.html.erb

 <div class="row">    <div class="col-md-10 col-md-offset-1">        <div class="table-responsive myTable">            <table class="table listing text-center">              <tr class="tr-head">                  <td>Date</td>                  <td>Description</td>                  <td>Amount</td>                  <td>Discount</td>                  <td>Paid</td>                  <td>Balance</td>              </tr>                <tr>                  <td></td>              </tr>                  <a href="#" class="toggle-form" style="float: right;" >Search</a>                <div id="sample">                     <%= form_tag xvaziris_path, remote: true, method: 'get', class: "form-group", role: "search" do %>                  <p>                      <center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", class: "form-control-search" %>                          <%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>                      </p>                      <% end %><br>                        <% if @xvaziris.empty? %>                        <center><p><em>No results found.</em></p></center>                                      <% end %>                    </div>                          <%= render partial: "xvaziri", collection: @xvaziris %>                    </table>              </div>          </div>      </div>  

_xvaziri.html.erb

<% balance = 0 %>    <tr  class="tr-<%= cycle('odd', 'even') %>">        <td class="col-1"><%= xvaziri.date.strftime('%d/%m/%Y') %></td>      <td class="col-3"><%= span_with_possibly_red_color xvaziri.description %></td>          <td class="col-1"><%= number_with_precision(xvaziri.amount, :delimiter => ",", :precision => 2) %></td>        <td class="col-1 neg"><%= number_with_precision(xvaziri.discount, :delimiter => ",", :precision => 2) %></td>        <td class="col-1 neg"><%= number_with_precision(xvaziri.paid, :delimiter => ",", :precision => 2) %></td>          <% balance += xvaziri.amount.to_f - xvaziri.discount.to_f - xvaziri.paid.to_f %>        <% color = balance >= 0 ? "pos" : "neg" %>        <td class="col-1 <%= color %>"><%= number_with_precision(balance.abs, :delimiter => ",", :precision => 2) %></td>    </tr>  

xvaziris_controller.rb

class XvazirisController < ApplicationController        before_action :set_xvaziri, only: [:show, :edit, :update, :destroy]          def index          @xvaziris = Xvaziri.where (["description LIKE ? OR amount LIKE ? OR paid LIKE ?", "%#{params[:search]}%","%#{params[:search]}%","%#{params[:search]}%"])           respond_to do |format|              format.js              format.html          end       end        def import          Xvaziri.import(params[:file])          redirect_to xvaziris_url, notice: "Xvaziris imported."      end        def show      end        def new          @xvaziri = Xvaziri.new      end        def create          @xvaziri = Xvaziri.new(xvaziri)          if              @xvaziri.save              flash[:notice] = 'Xvaziri Created'              redirect_to @xvaziri          else              render 'new'          end      end        def edit      end        def update          if @xvaziri.update(xvaziri)              flash[:notice] = 'Xvaziri Updated'              redirect_to @xvaziri          else              render 'edit'          end        end        def destroy          @xvaziri.destroy          flash[:notice] = 'Xvaziri was successfully destroyed.'          redirect_to xvaziris_url          end        private      # Use callbacks to share common setup or constraints between actions.      def set_xvaziri          @xvaziri = Xvaziri.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def xvaziri          params.require(:xvaziri).permit(:date, :description, :amount, :discount, :paid)      end    end  

search.js

$(document).on('page:change', function () {      $("div#sample").hide();        $("a.toggle-formed").click(function(event) {          event.preventDefault();          $("div#sample").fadeToggle();      });  });  

index.js.erb

$(#which_id?).append("<%= j render xvaziri %>");  

How would I link the id in order to retrieve all the data from xvaziris#index page in js format ?

I added remote: true, respond to format.js etc

Any suggestions are most welcome.

Thank you in advance.

ruby rails delete space after link_to without HAML

Posted: 06 Jul 2016 07:39 AM PDT

I am programming an app with Ruby on Rails and, in some views, I would like to get rid of the automatic whitespace triggered by the 'link_to' helper.

<%= link_to liker.first_name.capitalize, user_path(liker) %>     <!-- Example of link with a user's firstname (who liked a given content), redirecting to it's user profile -->

I have read this post, which talks about using HAML (that I do not use). Isn't it possible to delete this tiny whitespace only using Ruby on Rails?

trouble coding links which insert search values into ransack form

Posted: 06 Jul 2016 07:08 AM PDT

I've coded in a page in which data from a database is pulled and subsequently when I click on what is displayed it enters a corresponding value into the search function on the application and displays the results, the code can be seen below:

course view:

<!-- Index of all Courses -->  <% provide(:title, "Course") %>    <!--containers for design/layout -->   <div class = "signinstyle">    <div class = "row">      <!--Page information -->             <%= form_tag(degree_new_path, :method => "get", id: "search-data") do %>                  <table border="1" class="table">                <thead>                  <tr>                    <th>Courses</th>                  </tr>                </thead>                <tbody>                  <% @ads.each do |degree| %>                      <tr>                       <td> <%= link_to degree.cname, keyword_search_path(search: degree.cname) %>                                           </td>                  </tr>                  <% end %>                </tbody>              </table>        <%= submit_tag "Select" %>        <% end %>        <!--closing the design/layout containers -->       </div>  </div>      degree controller (the above view is within this):  class Degree < ActiveRecord::Base      def Degree.search(search)      where("cname LIKE ? OR ucas LIKE ?", "%#{search}%", "%#{search}%")    end  end  

search controller (as I use my keyword search in the view):

  def keyword_search      @search = Degree.all.select(:uname, :cname, :ucas, :duration, :qualification, :entry).distinct.order(id: :ASC)      if params[:search]        @search_degree = Degree.search(params[:search]).order('cname ASC')      end    end      def course      @select = Degree.all.select(:uname, :cname, :ucas, :duration, :qualification, :entry).distinct.order(id: :ASC)      if params[:search]        @select_degree = Degree.search(params[:search])      end    end  

I'm trying to replicate the above code so I can click on similar links which will enter data into the ransack search function I have but have been unable to do so, if anybody could help me out it would be appreciated. Below is the code I'm currently trying to get to work:

Searches controller:

  def adsearch      @adsearch = Degree.ransack(params[:q])      @data = @adsearch.result      @adsearch.build_condition if @adsearch.conditions.empty?      @adsearch.build_sort if @adsearch.sorts.empty?    end  

the view file:

<!-- Index of all Courses -->  <% provide(:title, "Course") %>    <!--containers for design/layout -->   <div class = "signinstyle">    <div class = "row">      <!--Page information -->             <%= form_tag(degree_new_path, :method => "get", id: "search-data") do %>                  <table border="1" class="table">                <thead>                  <tr>                    <th>Courses</th>                  </tr>                </thead>                <tbody>                  <% @ads.each do |degree| %>                      <tr>                        <td> <%= link_to degree.subject_group, adsearch_path(name: ucas & value: degree.ucas_letter) %>                            </td>                  </tr>                  <% end %>                </tbody>              </table>        <%= submit_tag "Select" %>        <% end %>        <!--closing the design/layout containers -->       </div>  </div>  

With the last two exerts of code it displays what I'm asking it to display on the initial view but doesn't enter the value I wish it to enter into the ransack search and as such doesn't create a search when clicked upon like the first example does.

Rails jquery atocomplete redirect to user

Posted: 06 Jul 2016 07:10 AM PDT

I am using rails-jquery-autocomplete and have failed to achive redirect to selected user.

This is my form:

  <%= form_tag users_path, method: 'get', id: 'search-form' do %>        <%= autocomplete_field_tag :search, 'Find your friends...', home_autocomplete_user_username_path, 'min-length' => 1, class:'search_field', onfocus: 'if($(this).val()=="Find your friends..."){$(this).val("");};', onblur: 'if($(this).val()==""){$(this).val("Find your friends...");};' %>    <% end %>  

It redirects to users_path, where it shows only selected user - but I want to redirect to his show page.

Actually I achived redirect to user adding:

    $('#search').bind('railsAutocomplete.select', function(event, data){        $('#search-form').submit();        window.location.href = '/users/' + data.item.id;      });  

But I think it is not the best solution and there are better ones. Thank you in advance for suggestions.

Rails: undefined method `id' for nil:NilClass

Posted: 06 Jul 2016 06:37 AM PDT

I am rendering form like that:

= f.fields_for :files do |files_form|    = render('file_form', f: files_form)  

In the _file_form.html.slim I have such a code:

- id = f.object.id  - file= f.object.files.first    li.panel.panel-default    .panel-heading role="tab" id="heading"      a.file-heading data-toggle="collapse" data-parent="#files" href="#collapse#{id}"        div.clearfix role="button"          span = f.object.name    .panel-collapse.collapse-in id="collapse#{id}" role="tabpanel"      .panel-body        .clearfix = link_to(t('shared.destroy'), '#', class:'btn btn-warning btn-sm discard-file pull-right')        .form-group          = f.label(:name, t('activerecord.attributes.file.name'))          = f.text_field(:name, class: 'form-control')          = f.label(file.id) //my problem  

everything works fine until I try to get label with the file id.

Error message: undefined method `id' for nil:NilClass

It looks like is not initialized but actually, when I check it in debugger before line with file.id, it is initialized and I can easily check it value.

When I'm using :id instead of file.id, everything work fine. Why?

Why file is nil class when i trying to retrieve id (or any other data) from it?

trying to connect server for ruby development

Posted: 06 Jul 2016 06:25 AM PDT

hi so im trying to get started with ruby and im having trouble setting up my server i did all the gems installing and stuff have a mysql2 server running but i cant connect to it trough my local hosti keep getting a error

so ive tried changing the default server gem that is puma dont even know what that is to webrick wich was recommended and my active record database to mysql2 i get this a error ill upload my server client connections and gemfile and such if it of some help

but what im basicallytrying to do is setting up a server to test my ruby apps

enter image description here

Dragonfly validation issue

Posted: 06 Jul 2016 06:14 AM PDT

I'm having an issue getting Dragonfly to run properly while following this tutorial. My model has been adjusted

# avatar  dragonfly_accessor :avatar  validates_property :format, of: :avatar, in: [:jpeg, :jpg, :png], case_sensitive: false,                     message: "should be either .jpeg, .jpg, .png", if: :avatar_changed?  

dragonfly.rb has the imagemagick plugin

Dragonfly.app.configure do    plugin :imagemagick    ...  

The schema for companies has the avatar_uid string.
The new/edit view has an <%= f.file_field :avatar %>

I'm able to pick an image from my disk (a normal .jpg image file) but every time I try to save it I'm getting the following error:

DRAGONFLY: shell command: 'identify' '-ping' '-format' '%m %w %h' '/var/folders/vp/k1zt15v54hg2945r9xpw0x980000gn/T/dragonfly20160706-75620-wb2b34'  DRAGONFLY: validation of property format of avatar failed with error Command failed ('identify' '-ping' '-format' '%m %w %h' '/var/folders/vp/k1zt15v54hg2945r9xpw0x980000gn/T/dragonfly20160706-75620-wb2b34') with exit status 1 and stderr identify: no decode delegate for this image format `' @ error/constitute.c/ReadImage/504.  

As the error states no decode delegate for this image format I print my list of supported images with the console command identify -list format

...  JPE* JPEG      rw-   Joint Photographic Experts Group JFIF format (80)  JPEG* JPEG     rw-   Joint Photographic Experts Group JFIF format (80)  JPG* JPEG      rw-   Joint Photographic Experts Group JFIF format (80)  JPS* JPEG      rw-   Joint Photographic Experts Group JFIF format (80)  ...  

I'm out of ideas. You guys have any? Thx!

Creating an RSS reader in Rails

Posted: 06 Jul 2016 05:56 AM PDT

Using the Feedjira gem, how would one go about parsing feeds in an app where users can log in and set up their own feeds, then display those feeds in a view. My current understanding is to use a 'Feed' and 'Entry' model/controller however with the additional 'User' model/controller this enters three nested resources territory which I have discovered requires polymorphic associations? I've found a few sources on using the Feedjira gem but none have given me a concrete understanding of how to use it. For example creating a model like

class Entry < ActiveRecord::Base      def self.update_from_feed(feed_name)      feed = Feed.find_by_name(feed_name)      feed_data = Feedjira::Feed.fetch_and_parse(feed.feed_url)      add_entries(feed_data.entries, feed)    end      private    def self.add_entries(entries, feed)      entries.each do |entry|        break if exists? :entry_id => entry.id            create!(              :entry_id     => entry.id,              :feed_id      => feed.id,              :url          => entry.url,              :title        => entry.title.sanitize,              :summary      => entry.summary.sanitize,              :description  => entry.content.sanitize,              :published_at => entry.published          )          end      end    end  end  

source

But I'm unclear in how this would interface with a feed controller and ultimately display a feed, or even just be able to access @entry.something on the view so I can work with it from there. I apologize if this question is too vague, let me know if I'm incorrect in the polymorphic associations assumption and if there is an easy implementation of the routing. Maybe a link to some documentation that could give me a better understanding of my current situation.

undefined method `+' for nil:NilClass (NoMethodError) - Ruby

Posted: 06 Jul 2016 05:57 AM PDT

When the rails application is run, I get the following error which is shown clearly in an image, which is as below;

error.png

index.html.erb

<% balance = 0 %>    <div class="row">        <div class="col-md-10 col-md-offset-1">            <div class="table-responsive myTable">                <table class="table listing text-center">                  <tr class="tr-head">                      <td>Date</td>                      <td>Description</td>                      <td>Amount</td>                      <td>Discount</td>                      <td>Paid</td>                      <td>Balance</td>                  </tr>                        <%= render partial: "xvaziri", collection: @xvaziris %>                    </table>              </div>          </div>      </div>  

_xvaziri.html.erb

<tr  class="tr-<%= cycle('odd', 'even') %>">        <td class="col-1"><%= xvaziri.date.strftime('%d/%m/%Y') %></td>      <td class="col-3"><%= span_with_possibly_red_color xvaziri.description %></td>          <td class="col-1"><%= number_with_precision(xvaziri.amount, :delimiter => ",", :precision => 2) %></td>        <td class="col-1 neg"><%= number_with_precision(xvaziri.discount, :delimiter => ",", :precision => 2) %></td>        <td class="col-1 neg"><%= number_with_precision(xvaziri.paid, :delimiter => ",", :precision => 2) %></td>          <% balance += xvaziri.amount.to_f - xvaziri.discount.to_f - xvaziri.paid.to_f %>        <% color = balance >= 0 ? "pos" : "neg" %>        <td class="col-1 <%= color %>"><%= number_with_precision(balance.abs, :delimiter => ",", :precision => 2) %></td>    </tr>  

Any suggestions are most welcome.

Thank you in advance.

ActiveRecord::NoDatabaseError: local user with ID does not exist

Posted: 06 Jul 2016 05:55 AM PDT

Developing an API-only Rails app to consume data from an API, filter out a number of the fields, and then broadcast fields we want public.

My app was returning data normally, but I realized that on the source API level, we changed the data type for one of the fields of data we're exposing. To accommodate, I committed my work, checked out a new branch, ran a migrations to change a data field's data type, decided I wasn't happy with how it worked, rolled back the migration, committed, and checkout out the master branch. The app is returning data as normal. However, now when I test my model's records in Rails Console using finder methods like .first, .last, etc., I get the error below. They were working fine before.

I've looked around and haven't seen any threads on this particular error (they all seem to deal with finding individual records for the show page) - although this, and this thread (by extension) seem closest. And checking the users on the db I'm using shows that the user ID ("501") in the error is not present.

What did I do and what do I need to do so that I can call finder methods again? Do I need to create that user referenced in the error in my db? (and why is it not the default user that I always use to connect to my db? Where did that user ID in the error come from? Does it even matter?)

ps - in case it's relevant, I used rake db:rollback to rollback my migration as per this thread.

Thanks in advance.

Rails Console

.2.1 :001 > KoboApi.first  ActiveRecord::NoDatabaseError: local user with ID 501 does not exist        from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/postgresql_adapter.rb:661:in `rescue in connect'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/postgresql_adapter.rb:651:in `connect'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/postgresql_adapter.rb:242:in `initialize'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-postgis-adapter-3.1.4/lib/active_record/connection_adapters/postgis_adapter.rb:51:in `initialize'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-postgis-adapter-3.1.4/lib/active_record/connection_adapters/postgis/create_connection.rb:37:in `new'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-postgis-adapter-3.1.4/lib/active_record/connection_adapters/postgis/create_connection.rb:37:in `postgis_connection'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:438:in `new_connection'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:448:in `checkout_new_connection'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:422:in `acquire_connection'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:349:in `block in checkout'      from /Users/toby/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:348:in `checkout'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:263:in `block in connection'      from /Users/toby/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:262:in `connection'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.5.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:571:in `retrieve_connection'  ... 13 levels...      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/commands/console.rb:9:in `start'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:68:in `console'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/commands.rb:17:in `<top (required)>'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:in `require'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:in `block in require'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:240:in `load_dependency'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:in `require'      from /Users/toby/code/projects/koboApi-broker/bin/rails:9:in `<top (required)>'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:268:in `load'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:268:in `block in load'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:240:in `load_dependency'      from /Users/toby/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:268:in `load'      from /Users/toby/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'      from /Users/toby/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'  

I'm definitely getting my records - they're coming into the database:

Rails dbconsole

koboApi_development=# select * from kobo_apis limit 1;    id  | lemurs_quantity | month_and_year | _geolocation | lemur_category | location_admin1 | location_admin2 | record_id | sighting_month | sighting_year  ------+-----------------+----------------+--------------+----------------+-----------------+-----------------+-----------+----------------+---------------   1365 |               1 |                |              | I_dont_remembe | antsiranana     | diana           |   1234567 | no_response    | 2013  (1 row)    koboApi_development=# \du                               List of roles   Role name |                   Attributes                   | Member of  -----------+------------------------------------------------+-----------   [user]    | Superuser, Create role, Create DB, Replication | {}  

from my schema

ActiveRecord::Schema.define(version: 20160705203507) do      # These are extensions that must be enabled in order to support this database    enable_extension "plpgsql"    enable_extension "postgis"      create_table "kobo_apis", force: :cascade do |t|      t.integer "lemurs_quantity"      t.date    "month_and_year"      t.text    "_geolocation"      t.text    "lemur_category"      t.string  "location_admin1"      t.string  "location_admin2"      t.integer "record_id"      t.string  "sighting_month"      t.string  "sighting_year"    end      create_table "my_spatial_table", force: :cascade do |t|      t.geography "polygon_data", limit: {:srid=>4326, :type=>"polygon", :geographic=>true}    end    end  

My database.yml

development:    adapter: postgis    encoding: unicode    postgis_extension: postgis      # default is postgis    postgis_schema: public          # default is public    schema_search_path: public,postgis    database: koboApi_development    pool: 5    test:    adapter: postgresql    encoding: unicode    database: koboApi_test    pool: 5    production:    adapter: postgresql    encoding: unicode    database: koboApi_production    pool: 5  

Soft delete with associations

Posted: 06 Jul 2016 06:12 AM PDT

I have three models:

User:

class User < ActiveRecord::Base    has_many :posts, :dependent => :destroy    scope :active, -> { where(deleted: false) }  end  

Post:

class Post < ActiveRecord::Base    belongs_to :user    has_many :comments, :dependent => :destroy      scope :active, -> { where(deleted: false) }  end  

Comment:

class Comment < ActiveRecord::Base    belongs_to :post    scope :active, -> { where(deleted: false) }  end  

Now, I am doing soft delete for User and I have column named deleted in all three tables(User, Post, Comment)

User destroy method:

def destroy    @user = user.find(params[:id])      if @user.update_attributes(deleted: true)      @user.posts.each do |post|        post.comments.update_all(deleted: true)      end        @user.posts.update_all(deleted: true)    end  end  

The above implementation takes more time when no. of posts and comments are high and it also creates N+1 query problem..

Same as above I have implemented destroy method for Post, I don't know how to do it efficiently..

I don't want to use any kind of gem.

Please tell me a better way to do soft deletion for these kind of associations..

rspec require lib only in one model

Posted: 06 Jul 2016 05:32 AM PDT

I'm using refile gem and wanna test the uploader with rspec. Since I'm using refile only for one model in the app I wanna avoid requiring it in rails_helper. If I try to require it as you see below then I will get require': cannot load such file -- refile/file_double (LoadError) error. What should I do?

rails_helper.rb

require 'devise'  require "pundit/rspec"  require 'capybara/rails'  require 'capybara/poltergeist'  

spec/models/company_spec.rb

require 'rails_helper'  require 'refile/file_double'  

Create FFMPEG process that keeps transcoding in Ruby

Posted: 06 Jul 2016 05:26 AM PDT

I am looking for a way to start a FFMPEG process to transcode a file, that gets appended every two seconds. Basically the file is created once (create-route), the ffmpeg process should be started, over the update-route the file gets updated and once it is not needed anymore (Destroy-route), it will be killed and the file be deleted. Currently I am usin Open3 with the following approach:

  Open3.popen3("ffmpeg", ffmpeg_args) { |stdin, stdout, stderr|      puts stderr.read    }  

However this does not seem to be the correct approach. Is there a better way to create a process and stop it later? Also how could this be achieved without a temporary file, but a pipe instead? The issue here is that the file arrives in chunks every two seconds.

Rails possible function arguments

Posted: 06 Jul 2016 07:49 AM PDT

I'm quite new to Rails and want to improve my workflow. I'd like to know where I can look up possible function parameters for general rails functions. E.g:

I want to use the render function. What arguments can I pass it?

In order to answer this question I went to api.rubyonrails.org. But this only tells me the function signature:

render(*args, &block)

and I don't now more than before.

To get more information I read through the Ruby on Rails Guide about Layouts and Rendering (which is great). But even if I found what I was looking for it's not an acceptable way to just quickly look up possible options. I'm searching for something more concise.

How would I know that I can pass in things like :partial or :layout to the function?

Looking through the actual source code is another option. But that's also not very handy.

This render function is just an example. This occurred to me in several places where I wanted to use a function and couldn't find good documentation of what it is actually capable of doing.

Rails API with Grape, polymorphic: true, touch: true is not working

Posted: 06 Jul 2016 05:12 AM PDT

I am developing a Rails 4.2.6 API app with a number of polymorphic associations, the problem is touch: true does not show the updated object.

class Post < ActiveRecord::Base    belongs_to :postable, polymorphic: true, touch: true  end    class Event < ActiveRecord::Base    has_many :posts, as: :postable  end    class Agenda < ActiveRecord::Base    belongs_to :event, touch: true    has_many :sessions, through: :days, class_name: 'AgendaSession'  end    class AgendaDay < ActiveRecord::Base    belongs_to :agenda, touch: true    has_many :sessions, class_name: 'AgendaSession'    delegate :event, to: :agenda  end    class AgendaSession < ActiveRecord::Base    belongs_to :agenda_day, touch: true    delegate :event, to: :agenda_day    has_many :posts, as: :postable  end  

I am trying to retrieve the Event's attribute 'hashtag' through Post.postable. For the sake of argument lets say I have an event with hashtag: '#rock_events' and a session that belongs to the same event.

@event_post = Event.first.posts.first  @session_post = AgendaSession.first.posts.first    # Through console (and rspec):    @event_post.postable.hashtag  >> '#rock_events'  @session_post.postable.event.hashtag  >> '#rock_events'    # Edit the event's hashtag:    Event.first.update(hashtag: '#pop_event')  >> true  @event_post.postable.hashtag  >> '#rock_events'  @session_post.postable.event.hashtag  >> '#rock_events'  

My current dirty fix is:

class Post < ActiveRecord::Base    belongs_to :postable, polymorphic: true, touch: true    belongs_to :event, foreign_key: :postable_id, touch: true    belongs_to :session, class_name: 'AgendaSession', foreign_key: :postable_id, touch: true  end    # and to call a post's parent's hashtag:    @event_post.postable.posts.find(@event_post.id).event.hashtag  @session_post.postable.posts.find(@session_post.id).session.event.hashtag  

I understand that I'm reloading all associations in order to get the updated event's hashtag. Anyone knows of a fix or a better work around for this predicament?

Thank You

what is this error in ruby on rails?

Posted: 06 Jul 2016 05:08 AM PDT

What mean error :

ArgumentError: wrong number of arguments (given 0, expected 2..3)  

i understand error ArgumentError: wrong number of arguments (0 for 1)

both error the same?

How to add a mark as read method to the public activity gem

Posted: 06 Jul 2016 07:30 AM PDT

How can i add a mark as read method to the Public Activity so that the count of the unread notifications can be displayed.

Nested form fields not showing in polymorphic association

Posted: 06 Jul 2016 04:47 AM PDT

Hi I have a polymorphic association with for a Document model for storing document uploads. I'm trying to submit the document attributes as a nested attribute via the associated model.

However, when I load the form, the nested field does not show. What am I missing?

Schema:

  create_table "documents", force: :cascade do |t|      t.json     "links"      t.integer  "linkable_id"      t.string   "linkable_type"      t.datetime "created_at"      t.datetime "updated_at"    end      add_index "documents", ["linkable_type", "linkable_id"], name: "index_documents_on_linkable_type_and_linkable_id", using: :btree  

Models:

class Document < ActiveRecord::Base    belongs_to :linkable, polymorphic: true    belongs_to :user    belongs_to :company      mount_uploaders :links, DocUploader  end        class CustomerPlan < ActiveRecord::Base    has_many :documents, as: :linkable    accepts_nested_attributes_for :documents  end  

Controller:

class CustomerPlanController < ApplicationController      def new      @customer_plan = current_company.customer_plans.build    end      def create      @customer_plan = current_company.customer_plans.build(customer_plan_params)        if @customer_plan.save        redirect_to @customer_plan, notice: 'Customer plan was successfully created.'      else        render :new      end    end      private      def cusomter_plan_params        params.require(:cusomter_plan_params).permit(:date, :name, :plan_type,           documents_attributes: [:id, links: []])      end  end  

Form:

<%= simple_nested_form_for @stock_plan, :html => { :multipart => true } do |f| %>    <%= f.error_notification %>        <%= f.input :date %>      <%= f.input :name %>      <%= f.input :plan_type %>        <%= f.simple_fields_for :documents do |d| %>        <p><b>Upload here:</b></p>        <%= d.file_field :links, multiple: true %>        <br>      <% end %>      <%= f.button :submit%>  <% end %>  

Integration of ruby on rails with AngularJS

Posted: 06 Jul 2016 07:01 AM PDT

I am trying to create a Ruby On rails application with AngularJS. I already tried this by following how to wire up ROR with angularJS Article with mySQL database , But could not able to get any benefit. As i am new to AngularJS integration with ROR I faced following terminal command problems while trying above mentioned Link, and the problems are like:

  • First problem in while I am trying rails g rspec:install
  • Second problem is due to npm install -g yo command and then
  • third is npm install -g generator-angular Please help me by sending another Article , So that i can go ahead with this. Thanks in advance.

Gravatar image not displaying

Posted: 06 Jul 2016 06:17 AM PDT

I'm working through the Michael Hartl's Ruby on Rails Tutorial, and I've added code to display a user's Gravatar image. But it doesn't display.

This is my users helper

module UsersHelper    # Returns the Gravatar (http://gravatar.com/) for the given user.    def gravatar_for(user)      gravatar_id = Digest::MD5::hexdigest(user.email.downcase)      gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"      image_tag(gravatar_url, alt: user.name, class: "gravatar")    end  end  

And this is my show.html.erb

<% provide(:title, @user.name) %>  <div class="row">    <aside class="col-md-4">      <section class="user_info">        <h1>          <%= gravatar_for @user %>          <%= @user.name %>        </h1>      </section>    </aside>  </div>

Passenger + NGINX + Rails not serving media to iOS

Posted: 06 Jul 2016 03:59 AM PDT

Initially I couldn't figure out for the life of me how to get media (videos & audio) streamed to any of the Safari browsers (OSX & iOS). Ended up I needed to setup NGINX and Rails to set X-Accel-Redirect header to point to internal location and redirect the request to the specified location set by the header:

config/environments/production.rb

config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'  

nginx.conf

server {      listen 0.0.0.0:3000;      server_name server.com;        root /home/v2/project/public;        passenger_enabled on;        passenger_set_header X-Sendfile-Type X-Accel-Redirect;      passenger_set_header X-Accel-Mapping /home/v2/project/public/uploads/storage36/uploads/files/=/storage/;        location /storage {         internal;         alias /home/v2/project/public/uploads/storage36/uploads/files;      }  }  

At first this seemed to solve the problem. Now it is not sending the media files only on iOS (Safari & Chrome).

How do I implement bootstrap dropdown in rails with categories

Posted: 06 Jul 2016 04:14 AM PDT

I'm wanting to implement Bootstrap's dropdowns in my rails project similar to the code below provided on Bootstrap's website:

<div class="dropdown">    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">  Dropdown      <span class="caret"></span>    </button>    <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">      <li><a href="#">Action</a></li>      <li><a href="#">Another action</a></li>      <li><a href="#">Something else here</a></li>      <li role="separator" class="divider"></li>      <li><a href="#">Separated link</a></li>    </ul>  </div>  

I currently have a section in the project where I can add new/edit categories for use in the main form. The code I currently have for an unformatted select/dropdown is:

<%= f.select :category_id, Category.all.map { |category| [ category.name, category.id ] }, class: "form-control" %>  

Which doesn't seem to apply any bootstrap formatting, I've tried changing the code around a bit to be:

<%= f.select :category_id, options_for_select([Category.all.map { |category| [ category.name, category.id ] }]), {}, class: "form-control" %>  

This gives the dropdown box a bootstrap style box, but the dropdowns under the default selection don't have any formatting similar to Bootstrap's example. One of my categories is just called Pages, but the text inside the selectbox in the code above just shows ["pages", 1] where 1 is the ID.

Any help with this would be greatly appreciated :)

Rollback issue in rails 4

Posted: 06 Jul 2016 03:57 AM PDT

When I save my data there is no commit. Roll back occurs.
This is occurred when I correct my validation error.
The selected value from drop down does not show when validation errors corrected and also the drop down does not works with the validation correction.
these three are interrelated. When I give full correct field data, only saved.If I correct the data, the drop down does not work, so the id doesnot passed. This makes the roll back. How I cure this error. This confuses me anyone help me.
Thank You.

How to get static link from assets pipeline

Posted: 06 Jul 2016 03:50 AM PDT

I am very new in Rails and still got stuck at get a link to javascript file. I am using Bower Rails to install xdLocalStorage and after installed, a received a folder xdLocalStorage at vendor/assets/bower_component.

In my app/assets/javascript/xdLocalStorage/application.js:

//= require xdLocalStorage  //= require_tree .  

In my config/initializers/assets.rb

Rails.application.config.assets.precompile += %w( xdLocalStorage/application.js )  

Now, I want to get the url to file in xdLocalStorage. But i could not. I had tried as the follow:

= asset_url 'xdLocalStorage/dist/scripts/xdLocalStorage.min.js'  

But it return 404.

Some people ask me why am I have to get url. The xdLocalStorage.min.js is not using for my website, it would be embed on another website and dynamically load by jquery. So I need to get url to this file.

And some people ask me why not move xdLocalStorage to public folder. Because I need it is be able to upgrade xdLocalStorage by Bower easier.

Please help me to get the above url. Rails version: 4

Devise sign up either by email or by mobile number

Posted: 06 Jul 2016 03:53 AM PDT

I can register a user getting both email address and mobile number in my application. But what I really want is to register user using either email or mobile as a primary authentication key. So that if a user provides email address, it must be saved in email field in database and if user provides mobile number, it must be saved in mobile field in database.

And also I would like to overwrite the confirmation method of mobile user and would like to send an message with activation key and inter the key in the application to activate registration. I think its not so hard, but I didn't get where to start. Please suggest me the favourable way to accomplish this task.

Using method in a where clause Rails Ruby Active Record

Posted: 06 Jul 2016 03:24 AM PDT

I wondering if it is posible to use a model instance method as a where clause query. I mean. I have a model School with a method defined

class School < ActiveRecord::Base      def my_method      users.where(blablabla).present?    end    end  

Is it posible to get something like:

School.all.where(my_method: true)  

I know that I can do something like:

School.all.map{|x| x if x.my_method}  

But this way has a huge penalization in performance compared to where query. Furthermore, the return of what I'm searching is an ActiveRecord Relation and map returns an array.

UPDATE:

Also there is another way to do it like:

School.all.joins(:users).where("users.attribute = something")  

But this do not fit exactly what I want for several reasons.

Thanks in advance

Suggestions for architecture of a Rails Application (Requires integration with numerous other applications)

Posted: 06 Jul 2016 02:51 AM PDT

I am working on rails application which is supposed to pull data from tools like jira, trac, gitlab, github, pivotal tracker,jenkins etc. The purpose is to draw analytics on top of this data. Also, the application would serve as a project management tool, where we would create tickets track status (just like jira). Now all the applications (jira, gitlab etc) should be in continual sync (two way) with the rails application.

Currently I have created sidekiq jobs which would pull data using the APIs in regular intervals. But I need to move it to a more robust and fault tolerant architecture (Using webhooks, queues , APIs) and also ensure two way sync. Please provide suggestions on architecture and tools to implement the same.

How to access channels/queues opened on a Bunny session?

Posted: 06 Jul 2016 02:45 AM PDT

I'm using Rabbit MQ's Ruby client (Bunny).

I moved the hole Bunny config and initializing process in an initializer.

How can I access channels/queues opened on a Bunny connection from inside a controller or a lib?

I get 'true' when I call Bunny::Session#open? but I cannot seem to figure out how to access everything I need in that session.

No comments:

Post a Comment