Tuesday, November 1, 2016

rails select depending on another select | Fixed issues

rails select depending on another select | Fixed issues


rails select depending on another select

Posted: 01 Nov 2016 07:30 AM PDT

i have license controller, license having user_id, product_id, version_id, product and version having relation between them i want to make depending select, when choosing a product the 2nd select get to me all the versions for this product

      <div class="field">      <%=f.label(":product_id", "Choose product")%>      <%=f.collection_select :product_id, Product.all, :id, :name, include_blank: true %>    </div>    <div class="field">      <%=f.label(":version_id", "Choose Version")%>      <%=f.grouped_collection_select :version_id, Product.all, :versions, :name, :id, :name, include_blank: true %>    </div>  

Ruby apply association on each item of collection

Posted: 01 Nov 2016 07:49 AM PDT

I am trying to access specific objects through associations applied one after the other on a collection. For example, one of my database request would be :

get_current_user.readable_projects.cards.find(params[:card_id]).tasks  

get_current_user returns a unique User, readable_projects a collection of projects that this user can read. So far, so good. However, each project has many cards, and I'd like to retrieve all the cards from each project I have in the collection, so that in this result I can do a find for a specific card, and then retrieve its tasks, the association between Card and Task being also a has_many.

I could iterate through the projects with a each, but the problem is I want to use the default behavior of a find, so that if in all the cards from all the projects I don't find the one I was looking for, the default RecordNotFound routine is triggered. I could also use find_by and raise the exception manually, doing something like that :

   @projects = get_current_user.readable_projects      @projects.each do |p|        @found = p.cards.find_by(id: params[:card_id])        if @found.present?          break        end      end      if @found.present?        @tasks = @found.tasks      else        raise ActiveRecord::RecordNotFound      end  

However my main objective is to get this card in a way anyone reading the code could easily understand what I am doing here.

My question is : is there a way to do such kind of request in one very understandable line ? Thank you in advance for your help.

Rails 4.2 model relationships has_many generated helper methods for objects

Posted: 01 Nov 2016 07:22 AM PDT

I wondering about the automated helper methods for objects automatically generated by rails.

class Car < ActiveRecord::Base     has_one :steering_wheel, inverse_of: car     has_many :windows, inverse_of: :car  end    class Window < ActiveRecord::Base     belongs_to :car, inverse_of: :windows  end    class SteeringWheel < ActiveRecord::Base     belongs_to :car, inverse_of: :steering_wheel  end  

With this relationship i can do

car = Car.first  car.create_steering_wheel  

But i would like also to create a new window like

car.create_window  

How is it possible to do this?

Why does the wrong object get tested in this RSpec setup?

Posted: 01 Nov 2016 07:45 AM PDT

I'm having trouble with an RSpec test, and I suspect it may be to do with my explicit use of subject in the before block. Notably, I am testing ActiveRecord objects that have a has_many / belongs_to relationship. This is my failing test, in which I'm trying to assert that the parent has some behaviour based on the event of adding the child:

subject { FactoryGirl.create(:parent) }  let(:child) { FactoryGirl.build(:child) }    context "with added child object" do    before { subject.children << child }    its(:foo) { is.expected_to eq("bar")  end  

In my parent model I have some simple logic based on adding the child record which works outside of the test. Since it doesn't work in the test, I switched to writing the spec part out long-form to try and understand why:

before do    puts "subject is #{subject}"    puts "child is #{child}"    subject.children << child     puts "#{child} is now attached to #{child.parent}"  end    it "has the correct response" do    puts "testing against subject #{subject}"    expect(subject.foo).to eq("bar")  end  

And the output I got suggests that something weird is happening - that the subject I attach the child to is a different one to the one in the setup and testing blocks:

subject is #<Parent:0x00561eddf1a7a0>                                                    child is #<Child:0x00561edcdd7fb0>  #<Child:0x00561edcdd7fb0> is now attached to #<Parent:0x00561edd11c040>  testing against subject #<Parent:0x00561eddf1a7a0>  

Am I doing something wrong with subject to cause this behaviour? Is there a better way to write this test?

How to add invalid records to has_many :through association

Posted: 01 Nov 2016 07:16 AM PDT

I have a house model with a has_many-association for rooms.

house = House.find 1  dining_room = Room.find 1  living_room = Room.find 2  

The living_room is not a valid dataset. So if I add the rooms to the house

house << dining_room  house << living_room  

the living_room wasn't added, because it's invalid.

How can I skip the validation when adding an existing record to a has_many-association?

How to search by rating post?

Posted: 01 Nov 2016 06:59 AM PDT

I use gem 'ransack' and gem 'ratyrate'. How to combine these two gem

I am trying to do here so

<%= f.select :rates_id, options_from_collection_for_select(RatingCache.all, "id", "avg"), {:prompt => ''} %>  

Gives an error message: "You tried to define an association named rates on the model Post, but this will conflict with a method rates already defined by Active Record. Please choose a different association name."

Rails has_many and belongs_to returns nil

Posted: 01 Nov 2016 06:58 AM PDT

I have two models 'articles' and 'bookmarks' and have associated them using a specific column 'article_doi' as foreign_key.

In article.rb,

has_many :bookmarks, class_name: 'Bookmark', foreign_key: "article_doi", dependent: :destroy  

In bookmark.rb, belongs_to :article, class_name: 'Article', foreign_key: "article_doi"

But when I do article_object.bookmarks, it returns a nil Also when I do bookmark_object.article, it returns nil.

What has gone wrong?

Find user by confirmation_token devise rails?

Posted: 01 Nov 2016 06:33 AM PDT

I need to find user by it's confirmation token, but in the most recent version of Devise and Rails 4, it doesn't seem to work.

I'm using:

User.find_by(confirmation_token: Devise.token_generator.digest(self, :confirmation_token, params[:confirmation_token]))  

What's wrong?

Facebook share button is not working?

Posted: 01 Nov 2016 05:54 AM PDT

I have a room model and I want to create a share button for facebook. So I decided to do this with the sharer url method. I want to have a facebook icon on the show.html.erb (room view) where a user or visitor can share the room on facebook. When I click on the link I am redirected to facebook where I have to enter the link manually and not automatically which I want to share. If I am updating the show.html.erb link_to into:

<%= link_to image_tag('facebook_icon_red.png'), 'http://www.facebook.com/sharer.php?u=<%= yield :url %>', :target => :blank %>  

Then I am getting an error:

enter image description here

How can I make this work?

application.html.erb

<!DOCTYPE html>  <html>    <head>  ...  ...      <!-- for Facebook -->                <meta property="og:title" content="<%= @room.listing_name %>" />      <meta property="og:type" content="room" />      <meta property="og:image" content="" />      <meta property="og:url" content="<%= room_url(@room) %>" />      <meta property="og:description" content="<%= @room.detailed_description %>" />    </head>    <body>      <!-- Facebook Sharing Settings-->      <div id="fb-root">      </div>      <script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>      <script type="text/javascript">      FB.init({          appId: MY_ID(SOME NUMBERS),          status: true,          cookie: true,          xfbml: true      });      FB.Canvas.setAutoResize();      </script>  ...  ...  ...    </body>  </html>  

show.html.erb (room)

...  <!-- Do you like this Accommodation? -->  <%= link_to image_tag('facebook_icon_red.png'), "http://www.facebook.com/sharer.php?u=", :target => :blank %>    FB.ui(     {       method: 'feed',       name: 'Facebook Dialogs',       link: 'http://developers.facebook.com/docs/reference/dialogs/',       picture: 'http://fbrell.com/f8.jpg',       caption: 'Reference Documentation',       description: 'Dialogs provide a simple, consistent interface for applications to interface with users.',       message: 'Facebook Dialogs are easy!'     },     function(response) {       if (response && response.post_id) {         alert('Post was published.');       } else {         alert('Post was not published.');       }     }  );  

Rails multi language in async way (AJAX)

Posted: 01 Nov 2016 05:02 AM PDT

i'm new in rails.

I have in my content in two languages, and then the controller will return only the content in a specific language. For that i'm trying to do this using Ajax. i'm trying to make a simple example using ajax with rails.

well this is my controller:

class WelcomeController < ApplicationController      def index        @init_content = Initial.get_content(params[:lang])        if request.xhr?          render :partial => "welcome/home"       end      end    end  

And i have a simple ajax call which on success would be nice to load a div wihout losing javascript bindings.

    $.get( "/", { lang: "EN" } )    .done(function( data ) {    $("#home").load(data)    });  

The response it seems ok but is not loading nothing and it perfoms an extra GET with the last characters of authenticity token and i don't understand why.

In another hand if i use $("#home").html(data) but it will lose all javascript binding.

The only way for me seems that i will have to get all the content in json format and make a javascript to fill my html elements.

How is the best way to do this using rails? Does rails have any method that reloads a view without losing the javascript bindings?

Is callback needed for loops containing API requests?

Posted: 01 Nov 2016 06:41 AM PDT

I'm on Rails and I use Koala in a cron job to import all comments Facebook.

Is it ok to use a for loop where each time I make a request and store the response? Or there is a risk for which the for restart before I get a response from Facebook all gets messed up?

In other words: Does the loop wait for the response or do I need a callback function?

Here is the loop:

def self.import_comments      # Access Facebook API      facebook = Feed.get_facebook_access        # Run 190 queries per cron job      for i in 1..190            id_of_latest_feed         = Feed.get_latest['fb_id']          id_of_latest_feed_checked = Option.get_feed_needle            # Check if there are more recent feeds than the latest checked          if id_of_latest_feed != id_of_latest_feed_checked              # Get the facebook id of the feed which comes after the latest checked              latest_feed_checked  = Feed.where( fb_id: id_of_latest_feed_checked ).first              this_date            = latest_feed_checked['fb_updated_time']              feed_to_check        = Feed.get_older_than( this_date )                unless feed_to_check.nil?                  # Get the ID of the feed to check                  fb_id = feed_to_check['fb_id']                  # Update needle                  Option.update_feed_needle_to( fb_id )                    # -------- REQUEST! --------- #                  # Get comments from Facebook                  @comments = facebook.get_object("#{ fb_id }/comments?filter=stream")                    # Save each comment                  @comments.each do |comment|                      if Comment.exists?(fb_id: comment['id'])                          # don't  do anyhting                      else                          # save the comment                      end                  end               end          end      end  end  

How to Dynamically add attributes from csv file

Posted: 01 Nov 2016 05:49 AM PDT

I am new to RoR. I want to dynamically add attributes from a csv file so that my code would be able to dynamically read any csv file and build the db (i.e. convert any CSV file into Ruby objects)

I was using the below code

csv_data = File.read('myData.csv')  csv = CSV.parse(csv_data, :headers => true, :header_converters => :symbol)    csv.each do |row|    MyModel.create!(row.to_hash)  end  

However it will fail for the following example

myData.csv

Name,id  foo,1  bar,10   

myData2.csv

Name,value  foo,1  bar,10  

It will result an error for myData2 because the value is not a parameter in MyModel

unknown attribute 'value' for MyModel.

I have thought about using send(:attrAccessor, name) but I was not sure how can I integrate it when reading from csv, any ideas ?

Creating new Rails project on Ubuntu returning error

Posted: 01 Nov 2016 05:04 AM PDT

I am currently new to the Linux OS (Ubuntu). I was once learning to develop Rails application on Windows but I found out that it is better to develop Rails applications on Linux since there are some limitations on Windows. I dual booted my computer so I can have Linux and Windows at the same time.

So I installed Ruby and Rails using the RVM (I followed this setup: https://www.youtube.com/watch?v=hiPQynmnsiI) and I created a test project named web and placed it on my desktop. There were no errors prior to the creation of the project but when I ran the command rails s it returned the following:

    /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler    /runtime.rb:94:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'uglifier'. (Bundler::GemRequireError)      Gem Load Error is: Could not find a JavaScript runtime. See https://github.com/rails/execjs for a list of available runtimes.      Backtrace for gem load error is:      /home/arjay/.rvm/gems/ruby-2.3.0/gems/execjs-2.7.0/lib/execjs/runtimes.rb:58:in `autodetect'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/execjs-2.7.0/lib/execjs.rb:5:in `<module:ExecJS>'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/execjs-2.7.0/lib/execjs.rb:4:in `<top (required)>'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/uglifier-3.0.3/lib/uglifier.rb:5:in `require'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/uglifier-3.0.3/lib/uglifier.rb:5:in `<top (required)>'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:91:in `require'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:91:in `block (2 levels) in require'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:86:in `each'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:86:in `block in require'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:75:in `each'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:75:in `require'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler.rb:106:in `require'      /home/arjay/Desktop/web/config/application.rb:7:in `<top (required)>'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:88:in `require'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:88:in `block in server'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:85:in `tap'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:85:in `server'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `<top (required)>'      /home/arjay/Desktop/web/bin/rails:9:in `require'      /home/arjay/Desktop/web/bin/rails:9:in `<top (required)>'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `load'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `call'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/command.rb:7:in `call'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client.rb:30:in `run'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/bin/spring:49:in `<top (required)>'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `load'      /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `<top (required)>'      /home/arjay/Desktop/web/bin/spring:14:in `require'      /home/arjay/Desktop/web/bin/spring:14:in `<top (required)>'      bin/rails:3:in `load'      bin/rails:3:in `<main>'      Bundler Error Backtrace:        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:90:in `block (2 levels) in require'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:86:in `each'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:86:in `block in require'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:75:in `each'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:75:in `require'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler.rb:106:in `require'        from /home/arjay/Desktop/web/config/application.rb:7:in `<top (required)>'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:88:in `require'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:88:in `block in server'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:85:in `tap'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:85:in `server'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `<top (required)>'        from /home/arjay/Desktop/web/bin/rails:9:in `require'        from /home/arjay/Desktop/web/bin/rails:9:in `<top (required)>'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `load'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `call'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/command.rb:7:in `call'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client.rb:30:in `run'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/bin/spring:49:in `<top (required)>'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `load'        from /home/arjay/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `<top (required)>'        from /home/arjay/Desktop/web/bin/spring:14:in `require'        from /home/arjay/Desktop/web/bin/spring:14:in `<top (required)>'        from bin/rails:3:in `load'        from bin/rails:3:in `<main>'  

Thank you for anyone who can help me out!

D3 pie chart: Uncaught Type Error - Cannot read property 'pie' of undefined

Posted: 01 Nov 2016 03:52 AM PDT

I am attempting to create a d3 pie chart based off of this resource.

However, I get the following error:

Uncaught Type Error - Cannot read property 'pie' of undefined

My code:

class PieChart extends React.Component {  constructor() {      super();    // - This is where the error is occuring!        this.pie = d3.layout.pie().value((d) => d.value);      this.colors = d3.scale.category10();    }    arcGenerator(d, i) {      return (          <LabeledArc key = {`arc-${i}`}                      data = {d}                      innerRadius = {this.props.innerRadius}                      outerRadius = { this.props.outerRadius }                      color = {this.colors(i)} />      );    }    render() {        console.log('Render Method Fires');      let pie = this.pie(this.props.data),          translate = `translate(${this.props.x}, ${this.props.y})`;        return (               <g transform={translate}>                  {pie.map((d, i) => this.arcGenerator(d, i))}                </g>          );        }  }  

I think I have everything setup correctly. Im using react-rails gem as well as the d3-rails. I had to download the d3.js and put it directly in my js folder to get rid of the 'cannot find d3'.

Can anyone point me in the right direction, maybe you have a better resource for adding d3 + react functionality in rails?

Adding a remote link to the flash

Posted: 01 Nov 2016 03:58 AM PDT

Hi so I'm working on a project and I want to be able to have a link in the flash that opens in a modal, so I need the link to be remote. So I have

flash[:link] = { text: "Click here",                   location: new_post_path,                   remote: true                  }  

but when the flash is loaded, it doesn't actually load as a remote link?

Any help fixing this would be greatly appreciated.

apache 2.4.18 + passenger 5.0.30 = 403 errors

Posted: 01 Nov 2016 02:46 AM PDT

I have installed fresh Ubuntu 16.04 server with apache 2.4.18, added passenger 5.0.30, rvm, rails, all following tutorials on their websites like this one: https://www.phusionpassenger.com/library/walkthroughs/deploy/ruby/ownserver/apache/oss/xenial/install_passenger.html

I did apt-get dist-upgrade to update all to newest version.

This is my second ubuntu install in one week which has the same problem. It runs apache alright, I can get directory file listing, but when accessing rails app public directory, i get 403 errors, although user rights on directory and files are correct.

"You don't have permission to access / on this server."

Here are my apache settings:

<VirtualHost *:80>    ServerName daskonzert.org    ServerAlias www.daskonzert.org    DocumentRoot "/media/i/www/daskonzert.org/public"    ErrorLog ${APACHE_LOG_DIR}/das_konzert_error.log    CustomLog ${APACHE_LOG_DIR}/das_konzert_access.log combined    RailsEnv production    RackEnv development    PassengerDefaultUser www-data    PassengerRuby /usr/local/rvm/gems/ruby-1.8.7-head/wrappers/ruby    <directory "/media/i/www/daskonzert.org/public">      Require all granted      Options FollowSymLinks      AllowOverride None      Order allow,deny      Allow from all      Options -MultiViews    </directory>  </VirtualHost>  

There was a bug in passenger regarding this issue, but was resolved last year supposedly.

Already tried this and some other advices for configuration file settings, doesnt help: I'm getting 403 error using passenger for rails in apache

Any ideas?

Mongoid not persisting array

Posted: 01 Nov 2016 02:45 AM PDT

Ok, I got an Model like so:

Class Campaign      include Mongoid::Document    ...    field :stats, type: Array, default: []    end  

And trying to persist changes to the stats property like so:

campaign[:stats] += [hash]  

When I inspect the object in memory, the changes are visible, however it is not being persisted to the db. I've found this answer which seems to address the issue (and I changed my code accordingly as previously I was trying with this:

campaign.stats << hash  

And neither approach is working. Any ideas why?

undefined method `pathname' for Sprockets::Asset

Posted: 01 Nov 2016 03:17 AM PDT

I have a problem in loading stylesheets/application and javascripts/applications in my layout/application.haml file. When I type "rails s" and refresh the page I see following error:

log from log/development.log file

ActionView::Template::Error (undefined method `pathname' for #<Sprockets::Asset:0x00000005375e10>):       5:     %meta{ content: 'IE=Edge,chrome=1', 'http-equiv' => 'X-UA-Compatible' }/       6:     %meta{ content: 'width=device-width, initial-scale=1.0', name: 'viewport' }/       7:     = csrf_meta_tags       8:     = stylesheet_link_tag 'application', media: 'all'       9:     = javascript_include_tag 'application'      10:       11:   %body    app/views/layouts/application.html.haml:8:in `_app_views_layouts_application_html_haml__541114027848535829_70097966813720'  

views/layout/application.haml

!!!  %html{ lang: 'en' }    %head      %meta{ charset: 'utf-8' }/      %meta{ content: 'IE=Edge,chrome=1', 'http-equiv' => 'X-UA-Compatible' }/      %meta{ content: 'width=device-width, initial-scale=1.0', name: 'viewport' }/      = csrf_meta_tags      = stylesheet_link_tag 'application', media: 'all'      = javascript_include_tag 'application'      %body      %nav.navbar.navbar-default        .container-fluid          .navbar-header            %span.navbar-brand #{AppConfig.workshops_name}          %p.navbar-text.navbar-right            Links should go here      .container-fluid        .row          .col-lg-12            = yield  

gemfile

source 'https://rubygems.org'    gem 'rails', '4.1.8'    gem 'pg'  gem 'draper'  gem 'decent_exposure'  gem 'decent_decoration'  gem 'devise'  gem 'simple_form', '~> 3.1.0rc'  gem 'bootstrap-sass'  gem 'haml-rails'  gem 'sass-rails', github: 'rails/sass-rails'  gem 'coffee-rails'  gem 'uglifier'  gem 'quiet_assets'  gem 'jquery-rails'  gem 'therubyracer', platforms: :ruby  gem 'travis'  gem 'ffaker'  gem 'faker'  gem 'konf'    group :development do    gem 'spring'  end    group :development, :test do    gem 'rspec-rails'    gem 'factory_girl_rails'    gem 'pry'  end    group :test do    gem 'database_cleaner'    gem 'shoulda-matchers', require: false  end    ruby '2.3.1'  

assets/stylesheets/application

/*   *= require_tree .   *= require_self   */  

assets/javascripts/application

//  //= require jquery  //= require jquery_ujs  //= require bootstrap-sprockets  //= require_tree .  

I don't know what else can be helpful. Does anyone knows what's going on here? Thanks in advance!

ActionView::Template::Error (PG::UndefinedColumn: ERROR: column does not exist)

Posted: 01 Nov 2016 02:56 AM PDT

model

Attempt 1

def challenge_date     deadline || date_started    end  

Attempt 2

def challenge_date    if deadline != date_started      [deadline, date_started].reject(&:blank?).join()    else      date_started    end  end  

Both attempts gave the error. I need the method to iterate through next_user_challenge

def next_user_challenge    user.challenges.where('challenge_date > ?', challenge_date).order('challenge_date ASC').first  end  

rails c

# some challenges will just have a deadline   id: 1,   name: "Publish a Novel",   deadline: Sat, 26 Nov 2016,   date_started: nil,   user_id: 117,    # some challenges will just have a date_started   id: 2,   name: "Write a Chp",   deadline: nil,   date_started: Thu, 20 Oct 2016,   user_id: 117,    # and some challenges will have both   id: 3,   name: "Run a Mile",   deadline: Thu, 26 Sep 2016,   date_started: Thu, 26 Sep 2016, # If challenge has both deadline and date_started then date_started will be the same date as the deadline   user_id: 117,  

the user cannot destroy a record in a rail 5 application after deployment with Capistrano?

Posted: 01 Nov 2016 02:11 AM PDT

I have developed a very simple apps for trying out deployment on AWS server with Rails 5.0.0.1 and ruby 2.3.1.

As a user, I can delete a record without any problems on my localhost:3000. However I cannot delete a record after I have successfully deployed to a AWS amazon server with Nginx, Puma and Capistrano at 35.161.251.52/contacts, if you want to try. The destroy link becomes a show link.

I have followed this tutorial at https://www.sitepoint.com/deploy-your-rails-app-to-aws/

Can anyone shine a light on this? Thanks a lot!

How to monkey-patch an ActionView module via prepend?

Posted: 01 Nov 2016 01:59 AM PDT

If you include a module Foo in a class SomeClass, then prepend that module with another module Bar, any method-overwriting inside Bar will not take effect in SomeClass. Example:

module Foo    def some_method      puts 'In Foo'    end  end    class SomeClass    include Foo  end    SomeClass.new.some_method # => 'In Foo'    module Bar    def some_method      puts 'In Bar'      super    end  end    Foo.prepend Bar    Foo.ancestors # => [Bar, Foo]    SomeClass.new.some_method # => 'In Foo'    class AnotherClass    include Foo  end    AnotherClass.new.some_method # =>   # 'In Bar'  # 'In Foo'  

I am trying to monkey-patch an ActionView helper method the following way:

In lib/core_extensions/action_view/helpers/url_helper/secure_link_to:

module CoreExtensions    module ActionView      module Helpers        module UrlHelper          module SecureLinkTo            def link_to(name = nil, options = nil, html_options = nil, &block)              html_options ||= {}              if html_options[:target].present?                html_options[:rel] = 'noopener noreferrer'              end                super(name, options, html_options, &block)            end          end        end      end    end  end  

and then in an initializer:

ActionView::Helpers::UrlHelper.prepend CoreExtensions::ActionView::Helpers::UrlHelper::SecureLinkTo  

However, this doesn't seem to work. My assumption - by the time the initializer executes, ActionView::Helpers::UrlHelper has already been included (in wherever it is supposed to be included) and thus the prepending doesn't seem to take effect. Does anybody know a solution to this?

Rails showing attribute at beginning and end of a date range

Posted: 01 Nov 2016 01:24 AM PDT

I am creating this report which shows for each product how many units were purchased, sold and returned. These values are already calculated in my controller and shown in my view.

I have a database table stockdiaries that contains columns ID, DATENEW, PRODUCT, LOCATION, UNITS, PRICE, REASON, STOCK.

STOCK is the current stock after a certain stockdiary.

Now I need to add 2 columns. Start Stock and End Stock.

And achieve this for each row:

Product: Product A

Start Stock: 10

Purchased: 5

Sold: -3

Returned: -1

End Stock: 11

Then using ransack I will be able to filter a date range and see how products moved during that period.

My controller SummaryConsignor, which refers to Stockdiary Model

class SummaryConsignorsController < StockdiariesController     def index     params.permit!      @q = Stockdiary.joins(:product, :location).where('products.CONSIGNOR is not null').group(:PRODUCT).select("SUM(CASE WHEN `REASON`='-1' THEN (UNITS) ELSE 0 END) AS SOLD, SUM(CASE WHEN `REASON`='-7' THEN (UNITS) ELSE 0 END) AS RETURNED, SUM(CASE WHEN `REASON`='6' THEN (1*UNITS) ELSE 0 END) AS RECEIVED, UNITS, DISCOUNT, DISCOUNT_CONSIGNOR, stockdiary.PRODUCT, REASON, STOCK").ransack(params[:q])      @summary_consignors = @q.result.paginate(:page => params[:page], :per_page => 30)      @summary_consignorsnp = @q.result      @amount_total = @q.result.map(&:total_amount).sum      @discount_total = @q.result.map(&:DISCOUNT).sum      @total = @q.result.map(&:total).sum      @gross_profit_total = @q.result.map(&:gross_profit).sum      @consignment_cost_total = @q.result.map(&:consignment_cost).sum      @profit_total = @q.result.map(&:profit).sum        respond_to do |format|      format.html        format.pdf do          pdf = SummaryConsignorPdf.new(@summary_consignorsnp)          pdf.render_file "report.pdf"          send_data pdf.render, filename: 'report.pdf', type: 'application/pdf', disposition: 'inline'        end      end    end  

My Model Stockdiary

   class Stockdiary < ActiveRecord::Base         include ActionView::Helpers::NumberHelper            belongs_to :product, :foreign_key => 'PRODUCT'          belongs_to :location, :foreign_key => 'LOCATION'          self.table_name = "stockdiary"          def total_amount       ( price = self.try(:PRICE) || 0         units = self.try(:UNITS) || 0         price * units)      end        def total       (          discount = self.try(:DISCOUNT) || 0         price = self.try(:PRICE) || 0         units = self.try(:UNITS) || 0         (price * units) - discount)      end          def gross_profit        location = product.location.try(:DISCOUNT_CONSIGNOR)        location ? (self.total * location) : 0      end        def consignment_cost          (self.total - self.gross_profit)       end        def profit          (self.total_amount - self.consignment_cost)      end        def suppliers_name             suppliers_name = self.product.suppliers.pluck(:NAME).join(', ')            end          class SummaryConsignor < Stockdiary          end  

My view summary_consignors index

 <% @summary_consignors.each do |summary_consignor| %>          <tr class="<%= cycle('odd', 'even') %>">            <td><%= link_to summary_consignor.product.NAME, { controller: :products, action: :edit, ID: summary_consignor.product.ID }, :target => "_blank" %></td>          <td><%= summary_consignor.product.extra1_detail.try(:DESCRIPTION) %></td>          <td><%= summary_consignor.product.extra2_detail.try(:DESCRIPTION) %></td>          <td><%= summary_consignor.product.category.NAME %></td>          <td><%= summary_consignor.product.location.try(:NAME) %></td>          <td><%= number_to_human summary_consignor.SOLD, precision: 0 %></td>          <td><%= number_to_human summary_consignor.RECEIVED, precision: 0 %></td>          <td><%= number_to_human summary_consignor.RETURNED, precision: 0 %></td>        </tr>  

My partial view for ransack filters:

<div class="large-4 small-6 columns" >      <%= search_form_for @q do |f| %>        <div class="large-6 small-6 columns" >        <%= f.label :DATENEW, "from date" %>        <%= f.text_field :DATENEW_gteq, 'datepicker' => true %>        </div>          <div class="large-6 small-6 columns" >        <%= f.label :DATENEW, class: "to_date" %>        <%= f.text_field :DATENEW_lteq, :as => :date_picker, class: "radius" %>        </div>      </div>        <div class="large-12 small-12 columns" %>      <%= f.submit "Search", class: " radius button" %>      <%= link_to 'Clear Filters', summary_consignors_path, class:"secondary button" %>      </div>        <% end %>  

Now thanks to @SteveTurczyn help I understand that by setting this on my controller:

from_date = DateTime.parse('2016-10-01')  to_date = DateTime.parse('2016-10-31').end_of_day     @stockopenclose = {}    products = Stockdiary.where('DATENEW >= ? AND DATENEW <= ?',from_date, to_date).pluck(:product).uniq.sort    products.each do |product|      movements = Stockdiary.where('DATENEW >= ? AND DATENEW <= ? AND PRODUCT = ?',from_date, to_date, product)      opening_value = movements.sort('DATENEW ASC').limit(1).pluck('STOCK').first    closing_value = movements.sort('DATENEW DESC').limit(1).pluck('STOCK').first      @stockopenclose[product] = [opening_value, closing_value]    end  

I get an array with the values I'm looking for (although for static dates).

So my 2 questions are:

1 What's the right way to show them in view?

2 How do I replace from_date and to_date values to use values entered on ransack search form?

Where can I find the document of present? method of ActiveRecord_Relation in Rails?

Posted: 01 Nov 2016 01:25 AM PDT

I'm new to Rails. When I'm studying Rails, I come across some methods which I don't know how to use. Then I try to Google, but the outcome is not very good.
For example, I defined a model User. In the UsersController, I defined index method. In this method, someone used the @users.present? method. I'm not sure what it is. So I want to know how the official site says about it.

Where can I find the explanation of this method.
Could you tell me the way to study methods like this?

Rails dependent destroy on non associated objects

Posted: 01 Nov 2016 03:23 AM PDT

I have two tables. 'articles' and 'bookmarks'. I want to define association between them.

the articles table have 'doi' column which is used in bookmarks table.

articles:

| doi| varchar(255) | YES  | MUL | NULL |  

bookmarks:

+-----------------+--------------+------+-----+---------+----------------+  | Field           | Type         | Null | Key | Default | Extra          |  +-----------------+--------------+------+-----+---------+----------------+  | id              | int(11)      | NO   | PRI | NULL    | auto_increment |  | user_profile_id | int(11)      | NO   | MUL | NULL    |                |  | device_id       | int(11)      | NO   | MUL | NULL    |                |  | article_doi     | text         | NO   |     | NULL    |                |  | disabled_at     | varchar(255) | YES  |     | NULL    |                |  | created_at      | datetime     | YES  |     | NULL    |                |  | updated_at      | datetime     | YES  |     | NULL    |                |  +-----------------+--------------+------+-----+---------+----------------+  

For some reasons I cannot use article's id to refer the article in bookmarks table. Now I want to add dependant destroy to all bookmarks that has that particular article's doi in the article_doi column (delete all bookmarks when an article is deleted). How can I achieve that?

Rails, Simple Form, Cocoon - nested attributes

Posted: 01 Nov 2016 12:34 AM PDT

I have a model for organisation and another model for ip. Ip is nested under a namespace folder called Stance.

The associations are:

Organisation

has_one :ip, class_name: Stance::Ip      accepts_nested_attributes_for :ip,  reject_if: :all_blank,     allow_destroy:   true  

IP

belongs_to :organisation, inverse_of: :ip  

I am using Cocoon to nest attributes from the IP table in the Organisation form. My organisation form is as follows:

<%= f.simple_fields_for :ip do |f| %>        <%= f.error_notification %>          <%= render 'stance/ips/ip_fields', f: f %>        <% end %>        <% !if @organisation.ip.present? %>         <%= link_to_add_association 'Manage Intellectual Property Policy ', f, :ip, partial: 'stance/ips/ip_fields' %>       <% end %>   

I have an if statement around the add association link because Organisation only has one ip policy.

I just tried all of this, but when i click on the remove association at the bottom of the IP form, the record doesnt actually get destroyed. I can see that because the console still shows the record attributes and when I go back to edit the organisation form, I expect to see the option to add another ip instance (which would then be the only ip instance). Instead, I don't get that link.

My organisation controller has:

  def new      @organisation = Organisation.new      @organisation.build_ip      end      def edit      @organisation.build_ip unless @organisation.ip    end      def organisation_params        params.fetch(:organisation, {}).permit(:title, :logo,  :comment,            ip_attributes:          [:id, :research_access, :teaching_access, :commercial_access, :ip_ownership,  :_destroy],              )      end  

What do I need to do to get the ip record to be destroyed when I click the remove link in the ip form fields?

Materialize label gets overlapped in production env

Posted: 01 Nov 2016 05:23 AM PDT

I'm using materialize for my web page, and the problem is the label gets overlapped with the field over the text, this issue occurs only in the production environment, but works fine in the develop

<div class="input-field col s12">    <%= f.text_field :phone, id: "phno", "data-parsley-error-message" => "Please enter your phone number.", required: true %>    <label for="phno">Phone</label>  </div>  

Elongated CURL output in rails

Posted: 31 Oct 2016 11:09 PM PDT

When you run CURL on the commandline, you'll see output similar to the following:

macbook:~ user$ curl google.com -o testgoogle.html    % Total    % Received % Xferd  Average Speed   Time    Time     Time      Current                                   Dload  Upload   Total   Spent    Left  Speed  100   262  100   262    0     0  10647      0 --:--:-- --:--:-- --:--:-- 10916  macbook:~ user$   

I find similar, strange elongated output such as the below, repeated frequently in my rails production.log file

[Tue Nov 01 16:37:51.617147 2016] [mpm_prefork:notice] [pid 15243] AH00171: Graceful restart requested, doing restart  [Tue Nov 01 16:37:51.767113 2016] [so:warn] [pid 15243] AH01574: module passenger_module is already loaded, skipping  [Tue Nov 01 16:37:51.770601 2016] [so:warn] [pid 15243] AH01574: module ssl_module is already loaded, skipping  [Tue Nov 01 16:37:51.772164 2016] [so:warn] [pid 15243] AH01574: module ssl_module is already loaded, skipping  [Tue Nov 01 16:37:51.772319 2016] [so:warn] [pid 15243] AH01574: module ssl_module is already loaded, skipping  [Tue Nov 01 16:37:51.935146 2016] [ssl:warn] [pid 15243] AH02292: Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)  [ 2016-11-01 16:37:52.0096 16202/7f00e9003780 agents/Watchdog/Main.cpp:538 ]: Options: { 'analytics_log_user' => 'nobody', 'default_group' => 'nogroup', 'default_python' => 'python', 'default_ruby' => '/home/ubuntu/.rvm/gems/ruby-2.1.4@global/wrappers/ruby', 'default_user' => 'nobody', 'log_level' => '0', 'max_pool_size' => '6'>  [ 2016-11-01 16:37:52.0158 16205/7f9c84e5d780 agents/HelperAgent/Main.cpp:650 ]: PassengerHelperAgent online, listening at unix:/tmp/passenger.1.0.15243/generation-26/request  [ 2016-11-01 16:37:52.0233 16211/7f31ba5fd7c0 agents/LoggingAgent/Main.cpp:321 ]: PassengerLoggingAgent online, listening at unix:/tmp/passenger.1.0.15243/generation-26/logging  [ 2016-11-01 16:37:52.0235 16202/7f00e9003780 agents/Watchdog/Main.cpp:728 ]: All Phusion Passenger agents started!  [Tue Nov 01 16:37:52.024250 2016] [mpm_prefork:notice] [pid 15243] AH00163: Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.20 OpenSSL/1.0.1f Phusion_Passenger/4.0.53 configured -- resuming normal operations  [Tue Nov 01 16:37:52.024270 2016] [core:notice] [pid 15243] AH00094: Command line: '/usr/sbin/apache2'  App 16230 stderr:  App 16230 stderr:  App 16230 stderr: %  App 16230 stderr:  App 16230 stderr: T  App 16230 stderr: o  App 16230 stderr: t  App 16230 stderr: a  App 16230 stderr: l  App 16230 stderr:  App 16230 stderr:  App 16230 stderr:  App 16230 stderr:  App 16230 stderr: %  App 16230 stderr:  App 16230 stderr: R  App 16230 stderr: e  App 16230 stderr: c  App 16230 stderr: e  App 16230 stderr: i  App 16230 stderr: v  App 16230 stderr: e  App 16230 stderr: d  App 16230 stderr:  App 16230 stderr: %  App 16230 stderr:  App 16230 stderr: Xferd  Averag  App 16230 stderr: e Speed   Time    Time     Time  Current  App 16230 stderr:  App 16230 stderr:  App 16230 stderr:  App 16230 stderr:  App 16230 stderr:  App 16230 stderr:  App 16230 stderr:  App 16230 stderr:  App 16230 stderr:  App 16230 stderr:           Dloa  App 16230 stderr: d  Upload   Total   Spent    Left  Speed  App 16230 stderr:  App 16230 stderr:   0     0  App 16230 stderr:  0     0    0     0      0      0 --:--:-- -  App 16230 stderr: -:--:-- --:-  App 16230 stderr: -:--     0  100   242    0  App 16230 stderr:   0  100   242      0   1196 --:--:-- --:--:-- --:--:--  1192  100   244  100     2  App 16230 stderr: 100   242      5    721 --:--:-- --:--:-- --:--:--   720  App 16230 stdout: ok  [ 2016-11-01 16:37:55.3612 16205/7f9c84da7700 Pool2/SmartSpawner.h:298 ]: Preloader for /var/www/railsapp started on PID 16230, listening on unix:/tmp/passenger.1.0.15243/generation-26/backends/preloader.66bb10  

Needless to say, no rails code calls/uses CURL. Has anyone encountered this weird log output before, and what caused it for you?

Add attribute to ActiveRecord_Relation results based on existence of relationship?

Posted: 31 Oct 2016 11:18 PM PDT

I have a users table, a notifications table, and a join table of notification_reads. I'm trying to write a scope for an ActiveRecord query that will return all of the notifications (Notification.all) with an additional field based on whether the user has a correlating notification_read for that notification.

I'm imagining it would look something like:

class Notification    scope :with_reads_by_user, -> (user) {      select("*", "[some sql that produces a boolean] as read")      .joins(:notification_reads)        .where(notification_reads: {user: user})    }  end  

Nothing I've tried has seemed to come close, though.

Making an image cover a whole div of fixed height - Rails Carrierwave CSS

Posted: 31 Oct 2016 11:00 PM PDT

I'm working in a rails Instagram-like project where users can submit posts, each with a corresponding photo.

My objective now is to create a div that contains both a header (with some information) and a photograph. (

So my html.erb is something like this:

<div class="post-content">    <div class="header">     <!-- some other code here -->    </div>    <div class="photo-container">      <%= image_tag(post.image_url, class:'img-responsive') %>    </div>  </div>  

The tricky bit is that: 1. I'd like to make the the "post-content" div of a particular 'fixed' size regardless of the size of image the user uploads. 2. The image to cover the whole "post-content" div without cutting out any overflow. 3. For the image to be responsive - I'm using Bootstrap.

So far my relevant scss code is like:

.post-content-panel {    width: 60%;     margin: 0 auto;    padding: 0;    // height: 300px; I'd like to fix this.  }      .photo-container img {      max-width: 100%;      height: auto;  }  

This works partially. The image is responsive, covers the whole div but unfortunately the height of the parent div expands or retracts according to the image height.

I've tried to: 1. Fix the post-content-panel height but this 2. Transform the image with transform: scale(0.5) but although the size is reduced the image doesn't cover the whole container div. 3. Standardise image sizes at upload in Carrierwave (gem I'm using in the backend). I used resize_to_fill and resize_to_fit without success (either the image is cut or it gets deformed.

How could I make this work. Is it a Carrierwave issue so I images are not cut when resized or could you see any css solution here regardless the size of the image. Thanks

Uncaught ReferenceError: FluxDispatcher is not defined

Posted: 31 Oct 2016 11:09 PM PDT

This is my first time attempting to use react. I am running into the following error which is being displayed below. Uncaught ReferenceError: FluxDispatcher is not defined. I belive I have required all the correct gems and javascript files but, I can't figure out why FluxDispatcher is not being defined. Below I have listed out some of files, please let me know if I need to provide any more information.

enter image description here

Gemfile

source 'https://rubygems.org'    gem 'rails', '4.2.2'  gem 'sqlite3'  gem 'sass-rails', '~> 5.0'  gem 'uglifier', '>= 1.3.0'  gem 'jquery-rails'  gem 'jbuilder', '~> 2.0'  gem 'awesome_print', '~> 1.7'  gem 'bootstrap', '~> 4.0.0.alpha5'  gem 'ancestry'  gem 'rails_admin'  gem 'react-rails'  gem 'flux-rails-assets'  gem 'lodash-rails'    source 'https://rails-assets.org' do    gem 'rails-assets-tether', '>= 1.1.0'  end    group :development, :test do    gem 'byebug'    gem 'web-console', '~> 2.0'    gem 'spring'  end  

appliction.js

//= require jquery  //= require jquery_ujs  //= require tether  //= require bootstrap  //= require lodash  //= require react  //= require react_ujs  //= require flux  //= require eventemitter  //= require components  //= require app  //= require_tree .  

app.js

//  var Constants = {    CHANGE_EVENT: 'change',    ADD_COMMENT: 'comments.add'  };    var Store = new _.extend({}, EventEmitter.prototype, {    _comments: [],      addComment: function(comment) {      this._comments[comment.id] = comment;    },      comments: function() {      return this._comments;    },      addChangeListener: function(callback) {      this.on(Constants.CHANGE_EVENT, callback);    },      removeChangeListener: function(callback) {      this.removeListener(Constants.CHANGE_EVENT, callback);    },      emitChange: function() {      this.emit(Constants.CHANGE_EVENT);    }  });    var AppDispatcher = new FluxDispatcher();    AppDispatcher.register(function(payload) {    var action = payload.actionType;    switch(action) {      case Constants.ADD_COMMENT:        Store.addComment(payload.comment);        Store.emitChange();        break;      default:        // NO-OP    }  });    // Actions  var Actions = new _.extend({}, {    addComment: function(params) {      AppDispatcher.dispatch({        actionType: Constants.ADD_COMMENT,        comment: params      });    }  });  

comment_list.js.jsx

var CommentList = React.createClass({      componentDidMount: function() {      Store.addChangeListener(this._onChange);    },      componentWillUnmount: function() {      Store.removeChangeListener(this._onChange);    },      render: function() {      console.log('rendering');      return (        <div>          {[].map(function(comment) {            return <Comment key={comment.id} {... comment} />;          })}        </div>      );    },      _onChange: function() {      this.forceUpdate();    }  });    //Actions  var Actions = new _.extend({}, {    addComment: function(params) {      AppDispatcher.dispatch({        actionType: Constants.ADD_COMMENT,        comment: params      })    }  });  

show.html.erb

<div class="row">    <h1>Title: <%= @post.title %></h1>  </div>  <div class="row">    <div class="col-md-6">      <p>        <%= @post.description %>      </p>    </div>    <div class="col-md-6">      <p>Comments:</p>      <%= react_component('CommentList') %>    </div>  </div>  

No comments:

Post a Comment