Thursday, May 19, 2016

Everyone to be radio_button on a new line table | Fixed issues

Everyone to be radio_button on a new line table | Fixed issues


Everyone to be radio_button on a new line table

Posted: 19 May 2016 06:59 AM PDT

How do everyone to be radio_button on a new line table?

    <tbody>  <%= f.collection_radio_buttons( :colection, Collection.all, :id, :name, {}, {class: "collection"}) %>  </tbody>  

Ruby on Rails: Use Engine's Variables / Models Outside of Mounted Area

Posted: 19 May 2016 06:52 AM PDT

So I'm using Ruby on Rails for my application, I'm using Thredded for the community aspect and Devise for the authentication aspect.

Although I believe this issue isn't specific to any of the actual Gems and more a general Ruby on Rails question.

To mount the Thredded Gem, I put this code in my route.rb file:

mount Thredded::Engine => '/community/'  

This makes the Thredded gem work perfectly from /community/.

I want to use the Thredded navigation across the entire site. However, I can only access things like Thredded.current_user or other specific Thredded variables within the /community/ section of the site.

Is there any way to mount the Thredded::Engine within /community/ but also have aspects of it avaliable outside of that scope?

Here is the Thredded Gem: https://github.com/thredded/thredded

Here is the Thredded navigation:

<nav class="thredded--navigation" role="navigation">    <ul class="thredded--user-navigation<%= ' thredded--user-navigation-standalone' if Thredded.standalone_layout? %>">      <% if signed_in? && Thredded.standalone_layout? %>        <li class="thredded--user-navigation--profile thredded--user-navigation--item">          <%= link_to thredded_current_user, user_path(thredded_current_user) %>        </li>      <% end %>        <%= render 'thredded/shared/nav/notification_preferences', messageboard: messageboard_or_nil %>      <%= render 'thredded/shared/nav/private_topics' %>        <% if Thredded.standalone_layout? %>        <%= render 'thredded/shared/nav/standalone' %>      <% end %>    </ul>    <div class="thredded--main-navigation">      <%= yield :thredded_breadcrumbs %>      <%= render 'thredded/search/form', messageboard: messageboard_or_nil %>    </div>  </nav>  

Here are the shared files the nav is rendering: https://github.com/thredded/thredded/tree/master/app/views/thredded/shared

Here is the Thredded Initializer file:

# frozen_string_literal: true  # Thredded configuration    # ==> User Configuration  # The name of the class your app uses for your users.  # By default the engine will use 'User' but if you have another name  # for your user class - change it here.  Thredded.user_class = 'User'    # User name column, used in @mention syntax and should be unique.  # This is the column used to search for users' names if/when someone is @ mentioned.  Thredded.user_name_column = :name    # The path (or URL) you will use to link to your users' profiles.  # When linking to a user, Thredded will use this lambda to spit out  # the path or url to your user. This lambda is evaluated in the view context.  Thredded.user_path = lambda do |user|    user_path = :"#{Thredded.user_class.name.underscore}_path"    main_app.respond_to?(user_path) ? main_app.send(user_path, user) : "#{user.to_param}"  end    # This method is used by Thredded controllers and views to fetch the currently signed-in user  Thredded.current_user_method = :"current_#{Thredded.user_class.name.underscore}"    # User avatar URL. rb-gravatar gem is used by default:  Thredded.avatar_url = ->(user) { user.profile_picture.url }    # ==> Permissions Configuration  # By default, thredded uses a simple permission model, where all the users can post to all message boards,  # and admins and moderators are determined by a flag on the users table.    # The name of the moderator flag column on the users table.  Thredded.moderator_column = :admin  # The name of the admin flag column on the users table.  Thredded.admin_column = :admin    # This model can be customized further by overriding a handful of methods on the User model.  # For more information, see app/models/thredded/user_extender.rb.    # ==> Email Configuration  # Email "From:" field will use the following  # Thredded.email_from = 'no-reply@example.com'    # Incoming email will be directed to this host  # Thredded.email_incoming_host = 'example.com'    # Emails going out will prefix the "Subject:" with the following string  # Thredded.email_outgoing_prefix = '[My Forum] '    # Reply to field for email notifications  # Thredded.email_reply_to = -> postable { "#{postable.hash_id}@#{Thredded.email_incoming_host}" }    # ==> View Configuration  # Set the layout for rendering the thredded views.  Thredded.layout = 'thredded/application'    # ==> Error Handling  # By default Thredded just renders a flash alert on errors such as Topic not found, or Login required.  # Below is an example of overriding the default behavior on LoginRequired:  #  # Rails.application.config.to_prepare do  #   Thredded::ApplicationController.module_eval do  #     rescue_from Thredded::Errors::LoginRequired do |exception|  #       @message = exception.message  #       render template: 'sessions/new', status: :forbidden  #     end  #   end  # end  

Rails ActiveModelSerialzer include with transform_key

Posted: 19 May 2016 06:51 AM PDT

I have ZoneSerializer

class Api::V1::ZoneSerializer < ActiveModel::Serializer    attributes :id, :name, :address, :description, :groupname, :key, :speed_limit      has_many :radius_user_groups  end  

And I set transform_key

ActiveModel::Serializer.config.key_transform = :camel_lower  

When I get response from server I get radiusUserGroups which is ok. But frontend sends also radiusUserGroups for includes, but there seems to be no autotransform feature for backend. Should I do this manually?

What is standard practise for grouping batches of records added to MySQL db in Rails?

Posted: 19 May 2016 06:50 AM PDT

The front-page of another website is being scraped hourly for post titles and links.

Currently there is only one table in the application (that is doing the scraping) related to storing this data which looks like,

  create_table "trending_items", force: :cascade do |t|      t.string   "title"      t.string   "link"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end  

There are 30+ records to be added on each scrape, and currently the only way to sort them after the fact is by created_at.

But it doesn't seem right.

  1. My thought is to create another table called batches with no columns added, and then add an index column for batch_id to trending_items table.

  2. The other alternative I thought of is to just add another column to trending_items which increments by 1 on each scrape.

What is the more proper way to deal with organization in this situation?

Tutorial for Android Login with Rails API and Devise without Token Authentication

Posted: 19 May 2016 06:50 AM PDT

I am following https://www.youtube.com/watch?v=QxffHgiJ64M&list=PLe60o7ed8E-TztoF2K3y4VdDgT6APZ0ka&index=1 to create a simple android login and registration function, i am using rails and devise without the token authentication for the server side. is there any tutorial for creating the rails part for the server (session and registration controller) ?

rake aborted! NoMethodError: undefined method `add_filter' for AutoHtml:Module

Posted: 19 May 2016 06:47 AM PDT

Getting this error while running rake db:migrate command on Rails 4. Working on a project developed by other company.Here is my code from catarse_auto_html.rb `module Shared::CatarseAutoHtml extend ActiveSupport::Concern

included do AutoHtml.add_filter(:email_image).with(width: 200) do |text, options| text.gsub(/http(s)?://.+.(jpg|jpeg|bmp|gif|png)(\?\S+)?/i) do |match| width = options[:width] %|| end end

def self.catarse_auto_html_for options={}    self.auto_html_for options[:field] do      html_escape map: {        '&' => '&amp;',        '>' => '&gt;',        '<' => '&lt;',        '"' => '"'      }      image      youtube width: options[:video_width], height: options[:video_height], wmode: "opaque"      vimeo width: options[:video_width], height: options[:video_height]      link target: :_blank    end  end    def catarse_email_auto_html_for field_data, options= {}    self.auto_html field_data do      html_escape map: {        '&' => '&amp;',        '>' => '&gt;',        '<' => '&lt;',        '"' => '"'      }      email_image width: options[:image_width]      link target: :_blank    end  end  

end end `

Rails tests for "(in)valid log-in" - explanation needed

Posted: 19 May 2016 06:37 AM PDT

I understand part of the code here (from Hartl's tutorial), however I'm confused about the following:

  1. I guess I still don't how testing works essentially, i.e. if say a "valid login" happens then shouldn't the "invalid login" test fail?
  2. The ordering of code lines. For instance in test "login with invalid information" if assert flash.empty? => false, then the test has alreaduy created a new sessions template (2nd line)
  3. "post login_path, session: { email: @user.email, password: "password"} line - i.e. if we give default values, how does the test work? How does it pull data for any user and matches it with the test code? . Note: added fixtures in .yml

Code here (Hartl tutorial book Ch. 8)

require 'test_helper'    class UsersLoginTest < ActionDispatch::IntegrationTest      # a special setup method to create a user     def setup       # creates a user by pulling it out the user from the .yml file in fixtures      @user = users(:sevda)    end      test "login with invalid information" do      get login_path       assert_template 'sessions/new'      post login_path, session: { email: "", password: ""}      assert_not flash.empty?      get root_path      assert flash.empty?    end      test "login with valid information" do      get login_path       # post the login path with the email corresponding to the user      # we can't actually put the password -> so we'll do the 2nd best thing, that is to standarise it on the word password, i.e. all users in the databse will have the password as the string 'password'      post login_path, session: { email: @user.email, password: "password"}      assert_redirected_to @user      follow_redirect!      assert_template 'users/show'      assert_select "a[href=?]", login_path, count: 0      assert_select "a[href=?]", logout_path      assert_select "a[href=?]", user_path(@user)    end  end  

Ruby on Rails Scope with params and SQL in Rails 4

Posted: 19 May 2016 06:55 AM PDT

Can someone please tell me what is wrong in this statement?

scope :between, -> (sender_id, recipient_id) do  where('(conversations.sender_id = ? AND conversations.recipient_id =?) OR (conversations.sender_id = ? AND conversations.recipient_id =?)', sender_id,recipient_id, recipient_id, sender_id)  

end

NetBeans put a red line under it and says Unexpected tLPAREN_ARG

Thank you.

Why use hstore extension over ActiveRecords serialization?

Posted: 19 May 2016 06:30 AM PDT

Rails introduced Postgres hstore support in Rails 4. But before that one could use Active Model Serialization like so:

serialize :preferences, Hash  

I'm a layman and wonder, what are the benefits to one over the other?

OAuth2::Error: Invalid grant with Doorkeeper

Posted: 19 May 2016 06:27 AM PDT

I'm building an API inside vagrant box using rails 5 api. I already manage to build an api in my local ( without vagrant box ).

I'm just confused my I'm always getting this

OAuth2::Error: invalid_grant: The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.  

which is I know that this I have new generate app id and secret.

client = OAuth2::Client.new( app_id, secret, site: 'http://0.0.0.0:3000/')    client.auth_code.authorize_url( redirect_uri: callback )    access = client.auth_code.get_token( code_here , redirect_uri: callback )  

by the way box configure like this:

server.vm.network :forwarded_port, guest: 3000, host: 3001  

And I run rails s -b 0.0.0.0

It has been 2 days that I'm trying to fix but no luck at all.

wrong redirection in Rails

Posted: 19 May 2016 06:27 AM PDT

I'm experiencing a really weird behavior in my Rails app. I have a nested resource Sensor and in its controller I have an action to import records from a csv file. The end of that action is:

redirect_to deployment_sensors_path   #venue_sensors_path's value is '/deployments/38/sensors' which looks good    

The problem is that the redirection goes to a wrong action 'location' in the same controller. With no output in the console showing a change in the redirection. I don't have any before_filters in that controller and my routes.rb looks like:

routes.rb

resources :deployments do    resources :sensors do      collection do        get 'location'      end    end  end  

Extras:

This weird behavior happens no matter what path is in the redirect_to.

If I change the action name from 'location' to anything else everything works just fine.

Writing deployment_sensors_path directly in the browser address bar works perfectly.

I'm using Rails 4.

Question:

It seems location is a reserved word for a render option to set the HTTP header. Could that be the problem? If not, What else can I do to debug this problem?

Faye Websocket: can't detect websocket connection?

Posted: 19 May 2016 06:12 AM PDT

https://devcenter.heroku.com/articles/ruby-websockets - tutorial this code is basically based on.

My rack middleware in app/middleware:

require 'faye/websocket'    class Messenger      def initialize(app)      @app = app    end      def call(env)      if Faye::WebSocket.websocket?(env)        Rails.logger.debug "socket connection"        ws = Faye::WebSocket.new(env)          ws.on :open do |event|          ws.send("Hello world")        end          ws.on :message do |event|          ws.send(event.data)        end          ws.on :close do |event|          p [:close, event.code, event.reason]          ws = nil        end      # Return async Rack response       ws.rack_response     else          Rails.logger.debug "ususal connection"          @app.call(env)      end    end  end  

Note the logging I added: basically, when I echo my server with websocket connection (ws://HOST:RAILS_PORT) it logs 'usual connection', hence, rack can't perform handshake with client.

P.S. I inserted Messenger middleware in the top of Rack stack.

Active Scaffold 3.4.37 render active scaffold issue with Rails 4.2.6 and Ruby 2.3.0

Posted: 19 May 2016 06:03 AM PDT

If I render active scaffold in a partial i.e

render :active_scaffold => "ledger_accounts"

I am getting the following error.

ActionView::Template::Error (No route matches {"action"=>"new", "controller"=>"ledger_accounts", "eid"=>"77d8f5b1eaefaab20858811ed44ce6b3"} missing required keys: [:controller]): 1: <% action_links = active_scaffold_config.action_links.collection 2: unless action_links.empty? -%> 3: 4: <%= display_action_links(action_links, nil, :skip_unauthorized => true) %> 5: <%= loading_indicator_tag(:action => :table) %> 6: 7: <% end %> app/views/ledger_accounts/ledger_accounts_index.html.erb:32:in `_app_views_ledger_accounts_ledger_accounts_index_html_erb__4071978264884595668_51420140'

In My route.rb file I have defined the route like i.e

resources :ledger_accounts do as_routes collection do

end  

end Please suggest me what to do?

How to pick minus except of two tables in Ruby on Rails?

Posted: 19 May 2016 06:26 AM PDT

I have two tables one of which include ids from the other one. How can I choose all the records from the first table that`s ids are not in the second table using RoR query interface?

getting error#17 from highcharts while using solid gauge from backbone rails

Posted: 19 May 2016 05:46 AM PDT

I am trying to use "solidgauge" chart from highcharts in backboneJS. Previously I had used a VU meter and it was working correctly. When I used solid gauge I am getting highcharts#17 error. As per this error either I am giving series.type or chart.type wrong else I don't have the necessary extension files. I have loaded the "highcharts.js", "highcharts-more.js", "highcharts-3d.js" and "exporting.js" files and the sibling VU meter worked.So i think there is something wrong with my chart options but can't seem to figure out what that is.Here is my chart configuration and I am giving the data for the series dynamically.I am using coffeescript.

scoreCard :   chart:     type: 'solidgauge'   title: null   pane:     center: ['50%', '85%']    size: '140%'    startAngle: -90    endAngle: 90    background:      backgroundColor: (Highcharts.theme &&                 Highcharts.theme.background2) || '#EEE'     innerRadius: '60%'     outerRadius: '100%'     shape: 'arc'   tooltip:     enabled: false   yAxis:      min: 0     max: 100     stops: [          [10, '#55BF3B']           [60, '#DDDF0D']           [90, '#DF5353']     ]     lineWidth: 0,     minorTickInterval: null,     tickPixelInterval: 400,     tickWidth: 0,     title:        y: -70     labels:        y: 16     plotOptions:      solidgauge:        dataLabels:          y: 5         borderWidth: 0         useHTML: true   credits:    enabled: false   series: [     {      name: "Pulse value"     }   ]  

I cant seem to figure out whether the fault is because of the chart configuration or any missing header file. Can anyone please help?

How to refresh view when a new model instance was created in background

Posted: 19 May 2016 05:58 AM PDT

Similar to the example in this blog post I want to set up my app. With the difference, that I want my view to refresh, when an object was created in one of my databases tables, not when a filesystem event happened.

Is there a gem similar to rb-fsevents, but watching a database/table ? How can I detect database changes in Rails without polling?

My view:

<table>      <tr>          <th> Device </th>          <th> State </th>      </tr>      <% @events.each do |event| %>      <tr>          <td> Motion Sensor </td>          <td> <%= event.state %> </td>      </tr>      <% end %>  </table>      

The controller/action:

require 'reloader/sse'    class DevicesController < ApplicationController    include ActionController::Live        def live_stream          @events = Event.all                    response.headers['Content-Type'] = 'text/event-stream'        sse = Reloader::SSE.new(response.stream)          begin          # monitor the database          # when a new object is created          # Send a message on the "refresh" channel          sse.write({ :data => new_obj }, :event => 'refresh')        rescue IOError          # When the client disconnects, we'll get an IOError on write        ensure          sse.close        end      end  end  

rspec and gem bullet test env fail

Posted: 19 May 2016 05:44 AM PDT

i want to run rspec with gem bullet finding all the weak spots. i'm doing as follows:

Gemfile

group :development, :test do    gem "bullet"  end  

config/environments/test.rb

  config.after_initialize do      Bullet.enable = true      Bullet.rails_logger = true      Bullet.raise = true # raise an error if n+1 query occurs    end  

spec/spec_helper.rb

    if Bullet.enable?      config.before(:each) do        Bullet.start_request      end        config.after(:each) do        Bullet.perform_out_of_channel_notifications if Bullet.notification?        Bullet.end_request      end    end  

but when i try to run rspec i get error

% rspec  /spec/spec_helper.rb:24:in `block in <top (required)>': uninitialized constant Bullet (NameError)  

Please help me solve this problem

Rails creating wall with microposts in facebook style

Posted: 19 May 2016 05:48 AM PDT

I have created some models:

User:

  • some unimportant fields

Activity:

  • user_id
  • type
  • post_id

Post:

  • content
  • some unimportant fields
  • List item

Follower:

  • user_id
  • follower_id

My models:

# app/models/follower.rb  class Follower < ActiveRecord::Base    belongs_to :user, class_name: 'User', foreign_key: 'user_id'    belongs_to :follower, class_name: 'User', foreign_key: 'follower_id'  end    # app/models/activity.rb  class Activity < ActiveRecord::Base    belongs_to :user    belongs_to :post    enum activity_type: [:create_post, :comment, :share, :like]  end    #app/models/post.rb  class Post < ActiveRecord::Base    has_many :activities, class_name: 'Activity', foreign_key: 'post_id'      has_many :users, through: :activities, source: :user do      def filter(types)        where('activities.activity_type IN (?)', types)      end    end      after_create do |post|      Activity.create(user: User.current, post: post, activity_type: :create_post)    end  end    # app/models/user.rb  class User < ActiveRecord::Base    has_many :activities, class_name: 'Activity', foreign_key: 'user_id'    has_many :active_relationships, class_name: 'Follower',                                foreign_key: 'follower_id',                                dependent: :destroy    has_many :passive_relationships, class_name: 'Follower',                                     foreign_key: 'user_id',                                     dependent: :destroy    has_many :following, through: :active_relationships,                         source: :user    has_many :followers, through: :passive_relationships,                         source: :follower      has_many :posts, through: :activities, source: :post do      def filter(types)        where('activities.activity_type IN (?)', types)      end    end      def follow(other_user)      active_relationships.create(user_id: other_user.id)    end  end  

Now I want to archive something like facebook's wall with posts. More specific, on homepage should display posts connected with last activities users who logged in user follow. But not every. I want to get posts wrote by myself, shared by myself and posts created, liked and shared by users who I follow. Without duplications, so if user1 creates post and user2 likes it, user1 should see his own post only one with annotations that user2 likes his post.
I tried with something like:

current_user.following.collect{|user|    user.posts.filter([      Activity.activity_types[:like],      Activity.activity_types[:create_post],      Activity.activity_types[:share],    ])  }  

But there are duplicates and I have to add my own posts.

I also want to paginate results. What is the best way to do it?

refactoring methods in rails4

Posted: 19 May 2016 05:45 AM PDT

I have notifications as polymorphic and comments also as polymorphic. So you can get notifications when somebody comments on your notifiables (product, post, product_customer, product_lead). There are also other types of notifications that are not relevant here.

So the flow:

  1. comment get's created
  2. comment creation triggers notification creation, so user he/she has one unchecked notification
  3. user sees he/she has the notification
  4. clicks on it, which takes him/her to the relevant page
  5. in the meantime notification turns to checked from unchecked and number goes down by one

OVERVIEW:

notification gets created like this:

if @comment.save    @comment.send_comment_creation_notification(@commentable)    respond_to :js  end    def send_comment_creation_notification(commentable)    commenters = ([commentable.user] + commentable.users).uniq - [ user ]    commenters.each do | commenter |      Notification.create(recipient_id: commenter.id, sender_id: user_id, notifiable: commentable, action: "commented")    end  end  

THINGS TO BE REFACTORED:

Problem: I have problems with points 4 and 5 from the flow. To trigger checking the notification and decrease the notification number I inserted a custom action when user clicks on the link. This action then redirects him to the desired page. At the moment the commentable object of the comment can belong to 4 types of classes (post, product, product_customer, product_lead) and some of them requires parent_id. Thanks to this it became a little messy and I have no idea how to clean this up.

My questions:

  1. Is this approach good or I should do something else?
  2. If it's good enough, how can I refactor it?
  3. Where should I put this code? I couldn't figure out anything but application controller.

link in views

_commented.html.erb

<%= link_to dropdown_checking_decreasing_user_notifications_path    (current_user, notifiable_type: notification.notifiable_type,    notifiable_id: notification.notifiable_id) do %>      

_commented.js.jbuilder

json.url dropdown_checking_decreasing_user_notifications_path(current_user,    anchor_param: "commentable_#{notification.notifiable_id}",    notifiable_type: notification.notifiable_type, notifiable_id: notification.notifiable_id)  

notifications controller / custom action

def dropdown_checking_decreasing    current_user.decreasing_comment_notification_number(params[:notifiable_type], params[:notifiable_id])    redirect_to notification_redirection_path(params[:notifiable_type], params[:notifiable_id])  end  

application controller

def notification_redirection_path(notifiable_type, notifiable_id)    if notifiable_type == "ProductCustomer"      product_customer = ProductCustomer.find(notifiable_id)      product_id = product_customer.product_id    elsif notifiable_type == "ProductLead"      product_lead = ProductLead.find(notifiable_id)      product_id = product_lead.product_id    end    route = case notifiable_type            when "Post"              posts_path(anchor: "post_#{notifiable_id}")            when "Product"              product_path(notifiable_id, anchor: "comment-panel")            when "ProductLead"              product_product_lead_path(product_id, notifiable_id, anchor: "comment-panel")          when "ProductCustomer"             product_product_customer_path(product_id, notifiable_id, anchor: "comment-panel")          end  end  

Need to create PDF using edit blob data in Rails

Posted: 19 May 2016 05:33 AM PDT

I am developing Rails application where need to create PDF using store pdf as a BLOB data in MySQL field.

Now i can download it using BLOB data but first i have to edit it means replace some content like {NAME} to original user name.

Now i tried to replace name in BLOB data which fetch from DB then create PDF using send_data but did not any changed and create issue in PDF generate.

bContent = @document.document_content.bContent.gsub(/{NAME}/, "ADOBE")    send_data(@new_content,              type: "application/pdf",              filename: file_name)  

angular rails app not working after putting controller to seperate file

Posted: 19 May 2016 05:49 AM PDT

I have a rails app which uses angular in front end. I have put all angular files in app/assets/javascripts/angular. I have one template folder which has all the views and app.js

angular/app.js

app = angular.module("appname", ['ui.router', 'ngResource', 'templates']);    app.config([      "$stateProvider", "$urlRouterProvider",      function ($stateProvider, $urlRouterProvider) {          $stateProvider              .state("home", {                  url: "/",                  controller: "homeCtrl",                  templateUrl: "angular/templates/home.html"              })      }  ]);        app.controller("homeCtrl", ["$scope", "$state", function ($scope, $state) {      }]);  

This works.. But when I try to move the controller into a different file it wont work and not showing any errors. Here is what I tried for moving it to different file

angular/app.js

app = angular.module("appname", ['ui.router', 'ngResource', 'templates', 'homeCtrl']);    app.config([      "$stateProvider", "$urlRouterProvider",      function ($stateProvider, $urlRouterProvider) {          $stateProvider              .state("home", {                  url: "/",                  controller: "homeCtrl",                  templateUrl: "angular/templates/home.html"              })      }  ]);  

Created below file in angular/controllers/homeCtrl.js angular/controllers/home-ctrl.js

app = angular.module("appname", []);  app.controller("homeCtrl", ["$scope", "$state", function ($scope, $state) {      }]);  

Below are the 2 lines I added to application.js

//= require angular/app  //= require angular/controllers/home-ctrl  

Here is the full application.js

application.js

//= require jquery  //= require angular  //= require angular-ui-router  //= require angular-resource  //= require angular-rails-templates  //= require_tree ./angular/templates  //= require angular/app         //added this now  //= require angular/controllers/home-ctrl    //added this now  //= require jquery_ujs  //= require toastr  //= require bootstrap-sass/assets/javascripts/bootstrap-sprockets  //= require jquery-fileupload/vendor/jquery.ui.widget  //= require jquery-fileupload/jquery.iframe-transport  //= require jquery-fileupload/jquery.fileupload  //= require turbolinks  //= require_tree .  

Could someone tell me what am doing wrong here??

Unable to pass array in curl using ruby %x command

Posted: 19 May 2016 05:34 AM PDT

Hi I am passing an array of ids in curl command in ruby application via %x(), but I am unable to add those throwing error as :

JSON_PARSING_ERROR: Unexpected character (d) at position   

Array : @m = ["d_sample_id1","d_sample_id2"]

Command used :

%x(curl --header 'Authorization: key=keynotmentioned' --header 'Content-Type: application/json' https://android.googleapis.com/gcm/send -d '{"registration_ids": "#{@m}", "collapse_key": "Turn", "data": { "title": "test", "sound": true,"body": "test", "badge": "1" , "content_available": 1 ,"url": ""}}')  

Showing json parse error , can you help me out from this ? Thanx in advance.

Rails set new dimentions image paperclip

Posted: 19 May 2016 05:23 AM PDT

Is there any way to set new dimensions to my_image and save it to AWS S3?

I have

my_image = Post.last.photo.image    geometry = Paperclip::Geometry.from_file(my_image.url)  

so i want to set new geometry and save it

geometry = 'my params'  my_image.save  

Of course i have my

  has_attached_file :image, :styles => { :large => "220x" ..other styles}  

My main goal set new dimensions during cropping photo with Jcrop

so when i receive new params like my_params=>"crop_x"=>"83", "crop_y"=>"24", "crop_w"=>"76", "crop_h"=>"76" set it as new style inside has_attached_file

Stub specific instances of a class in a functional test

Posted: 19 May 2016 05:30 AM PDT

I want to test that a specific icon gets displayed in the view for a User with a streak more than X no of days. So I need to stub a streak method of the User model.But I want that it stubs the method only for a specific user based on its uid. The test code is given below.

test "should display an icon for users with streak longer than 7 days" do      node = node(:one)      User.any_instance.stubs(:streak).returns([8,10])      get :show,           author: node.author.username,           date: node.created_at.strftime("%m-%d-%Y"),          id: node.title.parameterize      assert_select ".fa-fire", 1  end  

The return value is an array, the first value in the array is the no of days in the streak and the second value is the no of posts in that streak.

The line User.any_instance.stubs(:streak).returns([8,10]) stubs any instance of the User class. How can I stub it so that it stubs only those instances where :uid => 1?

Dynamic population of drop-down list Rails

Posted: 19 May 2016 06:57 AM PDT

I am trying to make 2 partials.

The first partial will be a dropdown list that shows only the objects(ManagerApprovals) associated with the current user, that list would be populated by the associated ManagerApprovals that have a boolean marked as true.

The 2nd partial, depending on the item chosen from the dropdown, a 2nd partial will be populated with an index of items associated with the chosen ManagerApproval.

My question is about the first partial. I am struggling to create the drop down list and could use some help. I cannot figure out the syntax for my form. Currently I have a controller like so.

manager_approval_controller.rb

class Admins::ManagerApprovalsController < ApplicationController     def index    @manager_approvals = ManagerApproval.all(table:params[:table], per_table: 4)   end     def show    @manager_approval = ManagerApproval.find(params[:id])   end  end  

My view is like this but is not correct

   <%= form_for [:admins, @manager_approval] do |f| %>      <% if current_admin.manager_approvals.blank? %>        <option>No Sub-Accounts added, Add one today!</option>    <% elsif current_admin.manager_approvals.all? { |ma| ma.manager_approved == false }%>        <option>No Sub-Accounts approved yet!</option>    <% else %>        <% current_admin.manager_approvals.each do |ma| %>          <% if ma.manager_approved == true %>            <%= f.select :manager_approval, options_for_select(ma.order(:manager_company).pluck(:manager_company)) %>          <% end %>        <% end %>    <% end %>  <% end %>  

I want a dropdown menu but I need it to populate based on the ManagerApproval being associated with the current admin and each ManagerApproval object having a boolean set to true.

Any help would be greatly appreciated

Build expression builder which will build expression and then through query filter tables at run time in rails

Posted: 19 May 2016 04:49 AM PDT

I want to filter out the data at run time , user can add how many conditions want to add on some specific fields in table and then after applying all user that meet with given expression will filter out. Similar type of filter is done in jira and redmine software. I dont want to make whole thing from scratch , is any type of gem available. I used ran sack but it has its limitation.

how to match fingerprint in rails?

Posted: 19 May 2016 04:18 AM PDT

I want to match fingerprint from database in rails, please any one will tell me how to store value of fingerprint in db and how to match it when user scan his fingerprint with existing value of his fingerprint with 90% of matching probability.

Rails: how to get the corresponding label attribute "for" with radio_button_tag

Posted: 19 May 2016 04:33 AM PDT

I want make the label text clickable, so that the corresponding radio button is set selected. For that i need to set a for attribute in the label with the id from radio button.

          # in html.erb            <li>              <%= radio_button_tag "size_id", size.id %>              <%= label_tag size.id, size.presentation %>            </li>  

the generated output:

              <li>                  <input type="radio" name="size_id" id="size_id_8" value="8">                  <label for="8">XL</label>                </li>  

The output i want is:

               <li>                  <input type="radio" name="size_id" id="size_id_8" value="8">                  <label for="size_id_8">XL</label>                </li>  

How can i get the id="size_id_8" from radio button to the label for="size_id_8" ?

Implement code executor in rails app like rails console

Posted: 19 May 2016 04:12 AM PDT

Any suggestion how to achieve this, I know its not correct to expose app environment.

For small tasks connecting to and opening rails console from remote systems is time consuming. Instead if we can have small front end to do tasks same like rails console.

Provide suggestions without considering authentication, security and etc.

Rails File_field Maximum stack size

Posted: 19 May 2016 04:08 AM PDT

I'm trying to upload a photo by clicking a div following this tutorial: https://jsfiddle.net/rustybailey/2b7dD/

However when i click the div i get this error
:Uncaught RangeError: Maximum call stack size exceeded

I know it's a loop error. However I don't understand why.

Here's my code:

Html

    <div align="left" class = "upload" id = "upload">      <%= f.file_field :image,:style => "display: none", hide_label: true,:id    => "imagem"%>      <div style = "margin-left: 15px" id = "foto">      </div>      </div>  

Css

.upload{  width:200px;  height:200px;  background-color: #000000;  display: block;  }  

Js

   $('#upload').on('click', function() {       $('#imagem').click();      });  

No comments:

Post a Comment