Monday, January 23, 2017

nokogiri wont parse the file using SAX handler | Fixed issues

nokogiri wont parse the file using SAX handler | Fixed issues


nokogiri wont parse the file using SAX handler

Posted: 23 Jan 2017 07:41 AM PST

I have xml file with header

<?xml version="1.0" encoding="utf-16"?>  

and also it contains the

<transmission xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">  

when used the SAX parser it wont parse. But when manually removed the encoding part and the attributes after transmission;XML parsing success. Being the file is large;I cant use only SAX.Is there any other way to parse this xml file without manually removing the encoding and transmission attributes.

Ruby Minitest: Access variables in setup-method

Posted: 23 Jan 2017 07:35 AM PST

How can I access variables that are defined inside the setup method in Minitest?

require 'test_helper'    class TimestampTest < ActiveSupport::TestCase    setup do      @ag = AG.create(..., foo = bar(:foobar))      @ap = AP.create(..., foo = bar(:foobar))      @c  = C.create(..., foo = bar(:foobar))    end      [@ag, @ap, @c].each do |obj|      test "test if #{obj.class} has a timestamp" do        assert_instance_of(ActiveSupport::TimeWithZone, obj.created_at)      end    end  end  

If I run this @ag, @ap and @c are all nil. bar(:foobar) on line 5-7 is needed to access fixture-data.

Storing user generated scopes / segmentation of model

Posted: 23 Jan 2017 07:26 AM PST

I'd love to hear what people think might be the best practice for this.

I have users which can manage a list of customers. I want them to be able to segment their customers.

For instance a segmentation can be customers who have in the last 5 days purchased an item. Or customers who have not purchased an item at all.

Ideally i'll allow the segmentation to follow several conditions such as:

Customers who have purchased an item in the last 5 days AND was registered less than 2 days ago.

How would you go about setting this up and storing it?

I can set columns for each condition, but conditions might have different variations in what scope they use. Furthermore it doesn't work if you want them to be able to set several segments.

Another idea is to use serialization, if so any thoughts on how to do this?

Ubuntu development configuration with SSL, Puma, and Rails

Posted: 23 Jan 2017 07:26 AM PST

Goal: get ssl working in development mode (ssl works fine in production on heroku)

My setup: Ubuntu 16.04 Rails 5.0.1 Puma 3.6.2

config/environments/development.rb

config.force_ssl = true   

I tried following along with this puma ssl how-to: https://gist.github.com/tadast/9932075 (I am not sure what github procol is regarding pasting above link content here vs referencing it)

if I then use the command line method to run puma

puma -b 'ssl://127.0.0.1:3000?key=/home/sean/.ssh/server.key&cert=/home/sean/.ssh/server.crt'  

I am getting Chrome's 'Not Secure' error when trying to access via the browser after attempting to add certificate to ubuntu.

sudo cp server.crt /usr/local/share/ca-certificates/  sudo update-ca-certificates    Updating certificates in /etc/ssl/certs...   0 added, 0 removed; done.  Running hooks in /etc/ca-certificates/update.d...  done.  

Should I should see 1 added here? I also tried copying server.crt to /etc/ssl/certs

If I proceed past chrome block I get console error:

SSL error, peer: 127.0.0.1, peer cert: , #<Puma::MiniSSL::SSLError: OpenSSL error: error:1407609C:SSL routines:SSL23_GET_CLIENT_HELLO:http request - 336027804>  

Instead of using puma on command line I tried adding to config/initializers/puma.rb

bind 'ssl://127.0.0.1:3000?key=/home/sean/.ssh/server.key&cert=/home/sean/.ssh/server.crt'  

and starting: rails s

I do not get any page load but console shows:

HTTP parse error, malformed request (): # 2017-01-23 10:04:43 -0500: ENV: {"rack.version"=>[1, 3], "rack.errors"=>#>, "rack.multithread"=>true, "rack.multiprocess"=>false, "rack.run_once"=>false, "SCRIPT_NAME"=>"", "QUERY_STRING"=>"", "SERVER_PROTOCOL"=>"HTTP/1.1", "SERVER_SOFTWARE"=>"puma 3.6.2 Sleepy Sunday Serenity", "GATEWAY_INTERFACE"=>"CGI/1.2"}

I also tried downgrading puma to 3.5.2

Where am I going wrong?

Test if a method is called inside a module method

Posted: 23 Jan 2017 07:23 AM PST

I have the following in my module:

module SimilarityMachine    ...      def answers_similarity(answer_1, answer_2)      if answer_1.compilation_error? && answer_2.compilation_error?        return compiler_output_similarity(answer_1, answer_2)      elsif answer_1.compilation_error? || answer_2.compilation_error?        return source_code_similarity(answer_1, answer_2)      else        content_sim = source_code_similarity(answer_1, answer_2)        test_cases_sim = test_cases_output_similarity(answer_1, answer_2)        answers_formula(content_sim, test_cases_sim)      end    end    ...    end  

I would like to test these "if conditions", to ensure that the right methods are called (all these methods are from SimilarityMachine module). To do that, I have:

describe SimilarityMachine do    describe '#answers_similarity' do      subject { answers_similarity(answer_1, answer_2) }      let(:answer_1) { create(:answer, :invalid_content) }        context "when both answers have compilation error" do        let(:answer_2) { create(:answer, :invalid_content) }          it "calls compiler_output_similarity method" do          expect(described_class).to receive(:compiler_output_similarity)          subject        end      end  end  

With both answers created I go to the right if (the first, and I'm sure of that because I tested before). However, my result is:

  1) SimilarityMachine#answers_similarity when both answers have compilation error calls compiler_output_similarity method       Failure/Error: expect(described_class).to receive(:compiler_output_similarity)           (SimilarityMachine).compiler_output_similarity(*(any args))             expected: 1 time with any arguments             received: 0 times with any arguments  

What am I doing wrong?

Outputting content onto rails website from Third Party API

Posted: 23 Jan 2017 07:23 AM PST

I am using the HTTParty Gem to access data from a third party API.

I have set up the model to successfully retrieve/parse the data from the other website.

What I do not know: What code is required in the controller to allow me to display the content in the view (and ultimately the website).

Here is my code for the model file called representatives.rb

require 'rubygems'  require 'httparty'    class Representative < ApplicationRecord    include HTTParty      base_uri 'whoismyrepresentative.com'      default_params :output => 'json'      format :json        def self.find_by_zip(zip)      get('/getall_mems.php', :query => {:zip => zip})    end    end    puts Representative.find_by_zip(92651).inspect  

Here are my Json results:

<HTTParty::Response:0x7fa591c4a778 parsed_response={"results"=>[{"name"=>"Dana Rohrabacher", "party"=>"R", "state"=>"CA", "district"=>"48", "phone"=>"202-225-2415", "office"=>"2300 Rayburn House Office Building", "link"=>"http://rohrabacher.house.gov"}, {"name"=>"Darrell Issa", "party"=>"R", "state"=>"CA", "district"=>"49", "phone"=>"202-225-3906", "office"=>"2269 Rayburn House Office Building", "link"=>"http://issa.house.gov"}, {"name"=>"Barbara Boxer", "party"=>"D", "state"=>"CA", "district"=>"Junior Seat", "phone"=>"202-224-3553", "office"=>"112 Hart Senate Office Building", "link"=>"http://www.boxer.senate.gov"}, {"name"=>"Dianne Feinstein", "party"=>"D", "state"=>"CA", "district"=>"Senior Seat", "phone"=>"202-224-3841", "office"=>"331 Hart Senate Office Building", "link"=>"http://www.feinstein.senate.gov"}]}  

So what do I need to put in the representatives_controller.rb as well as the view files at this point?

Thanks

Rails Spree shipping.

Posted: 23 Jan 2017 06:53 AM PST

How I can combined this two shipping into a single without double price for shipping. Thnks enter image description here

Specify Unicode Character in Regular Expression

Posted: 23 Jan 2017 07:30 AM PST

How can I create a ruby regular expression that includes a unicode character?

For example, I would like to the character "\u0002" in my regular expression.

How do I display an image from an attachment?

Posted: 23 Jan 2017 06:46 AM PST

I'd like to display an image, that I uploaded with CarrierWave, in the following code block. And ow can I define the image size?

  <%= simple_format(@employer.name) %>     <% if @employer.attachment.present? %>            <h4>Attachment</h4>            <div class="attachment">              <p>                <%= link_to File.basename(@employer.attachment.url),                  @employer.attachment.url %>               (<%= number_to_human_size(@employer.attachment.size) %>)  </p> </div>  <% end %>  

Cannot install gem march_hare

Posted: 23 Jan 2017 06:17 AM PST

I tried adding this to my Gemfile:

gem 'march_hare', '~> 2.22'  

Using bundle install I got this message:

Could not find gem 'march_hare (~> 2.22)' in any of the gem sources listed in  your Gemfile or available on this machine.  

On the topmost line in my Gemfile, I have this :

source 'https://rubygems.org'  

When I manually visit the rubygems and I m able to find this gem here :

https://rubygems.org/gems/march_hare

How do I install this gem? I don't understand what is happening.

Ruby on Rails - Default ascending sort bootstrap table for the filtered column

Posted: 23 Jan 2017 05:57 AM PST

I'm a newbie in Rails, I want sort data in some code and I stuck...

I have a problem with the default sorting (ASC) on my bootstrap table. I want to sort data by the 'Expires' column, but I'm not sure how in case of filters add attributes which will refer to only one column. Data-field added to the %th makes the whole table filled with dates...

Can somebody help me?

_index.haml

   %table.table-striped#users-table(data-toggle="table" data-search="true" data-classes="table table-no-bordered" data-show-columns="true" data-locale="pl-PL" data-pagination="true" data-sort-order="asc" data-sort-name="expired")    %thead      %tr        - index_columns(params[:filter]).each do |column|          %th(class="#{index_columns_head[column][:class]}" data-sortable="true" data-field="expired")            = index_columns_head[column][:head]      %tbody        (..)    :javascript    $('#users-table').bootstrapTable();  

users_helper.rb

  def index_columns_head      { name: { class: "col-lg-7",                head: "Name" },        active_subscriptions: { class: "col-lg-2",                                head: "Subscriptions" },        expired: { class: "col-lg-2",                   head: "Expires" },        clients_count: { class: "col-lg-2",                         head: "Customers" },        options: { class: "col-lg-2",                   head: "Option" } }    end      def index_columns_content(user)      { name: head(user),       active_subscriptions: subscriptions_count(user),       expired: subscription_expired(user),       clients_count: User.of_agent(user).count,       options: link_to('New Order', new_user_order_path(user_id: user)) }    end  

Get values from Javascript object in Rails controller

Posted: 23 Jan 2017 06:45 AM PST

I'm fairly new to Rails but I have a situation where a user can create a vacancy and select modules for that vacancy by dragging en dropping modules. Everytime something has changed (a module has been added/removes to the vacancy of the order has changed) I send a javascript object to the rails controller through AJAX and I want to extract the values from this object and story them in my DB.

My object will look like this:

addedModules = {     module: [        {module_id: '1', name: 'first-module', width: '3', height: '1', position: '1'},        {module_id: '5', name: 'fifth-module', width: '1', height: '1', position: '2'},        {module_id: '3', name: 'third-module', width: '4', height: '1', position: '3'},     ]  };  

In my controller I would like to go through every module and extract their module_id, name, etc.

AJAX block:

$.ajax({      type: "POST",      url: "../../../vacancies/" + <%= params[:vacancy_id] %> + "/update_with_modules",      data: "addedModules=" + addedModules  }).done(function (response) {      console.log(response);  });  

Is there a way to do so or is there a better solution?

Rails form with dynamic test bank

Posted: 23 Jan 2017 05:33 AM PST

I'm looking to create a question bank where the test creator can specify the number of question they would like to see for each category of the form.

Currently I loop through all of the question to build the form, and I'm not sure how to simply pull out only x number of questions per category.

@questions = AuditQuestions.where(question_active: 'Y', audit_forms_id: session[:audit_forms_id]).order(question_order_number: :asc)  

Table structure:

id audit_forms_id question_category question_title question_text question_order_number question_active  

data must be a two dimensional array of cellable objects

Posted: 23 Jan 2017 05:29 AM PST

I'm trying to print some data in a table using a condition, but it returns the following error: data must be a two dimensional array of cellable objects

data = [["Lançamento"]]  data += @lancamentos.map do |lancamento|    if lancamento.tipo == 'DESPESA'      [        lancamento.descricao_lancamento, lancamento.valor      ]    end  end  pdf.table data  

Slimpay Illegal state Error when try to call orders.get_mandates method

Posted: 23 Jan 2017 04:55 AM PST

When i try to call get_mandates method of Slimpay using 'https://github.com/novagile/slimpay' Gem it is giving me 903 Ambiguous handler methods mapped Error(http://prntscr.com/dz8goe).

Difference between broadcast , broadcast_to and broadcast_for in rails 5

Posted: 23 Jan 2017 04:51 AM PST

From the Rails Guide I found following three code snippets

ActionCable.server.broadcast("chat_#{params[:room]}", data)  

This simple broadcast sends the data to a specific chat room

while broadcast_to as shown below seems to send data to all chatrooms within a channel to which current user is subscribed .

WebNotificationsChannel.broadcast_to(    current_user,    title: 'New things!',    body: 'All the news fit to print'  )   

Here is another type of broadcast broadcast_for - for which i couldn't get any example .

My question is what is actual difference between these three and when to use each of 'em - thanks in advance

Why is this map not working?

Posted: 23 Jan 2017 04:42 AM PST

I have a list of associado, and I want to select only the ones where eh_proprietario returns true. This is the mapping:

@possiveis_associados = associados.map { |e| e if e.eh_proprietario}  

If I add a puts "#{e.eh_proprietario}" I can see it return true for two instances, but in my view, when I try to use this collection, I get an error because @possiveis_associados is nil.

<%= m.select :associado_id , options_from_collection_for_select(@possiveis_associados, :id, :razao_social), {include_blank: false}, {class: 'form-control'}%>  

What am I doing wrong here?

Selenium does not execute javascript

Posted: 23 Jan 2017 04:46 AM PST

I am using capybara with Selenium as its driver. I am trying to click on an element, which when clicked it will reveal a div, but the click never invokes javascript to do just that.

Below is the code I have

scenario 'currently used transport mode cannot be re-selected' do    expect(page).to have_css("h2.summary")  expect(find('h2.summary').text).to eq("Single event")  expect(page).to have_content("Change journey")  page.click_link("Change journey")  expect(find('#travel-times-preview').visible?).to be_truthy # FAILS here because of previous step not working    end  

error message

Capybara::ElementNotFound: Unable to find css "#travel-times-preview"

html

<a class="change-journey gray-text" href="#">Change journey</a>  

javascript code to execute

$(".change-journey").on("click", function(e){        var target = $(this).data("preview-target");        $('[data-preview-toggle="'+ target +'"]').toggleClass("hidden");        if($(this).text().indexOf('Change journey') > -1){          $(this).text("Close Preview");        }else{          $(this).text("Change journey");        }      e.preventDefault();    });  

While i can see the link being clicked, the underlying javascript is not executed.

How to use two different method with the same "name" from two different gems on the same rails model?

Posted: 23 Jan 2017 05:10 AM PST

The app (rails 4.2.7) i'm working on uses both carrierwave and paperclip for uploading image for two different fields on the same data model User (schema below).

create_table "users", force: :cascade do |t|    t.string   "email"    t.string   "first_name",             limit: 255    t.string   "last_name",              limit: 255    t.string   "avatar_file_name",       limit: 255    t.string   "avatar_content_type",    limit: 255    t.integer  "avatar_file_size"    t.datetime "avatar_updated_at"    t.string   "cv_file"  end  

The avatar field is a paperclip object and cv_file is a carrierwave uploader.

Now, for background processing of cv_file field, i'm using carrierwave_backgrounder gem and for avatar field i'm using delayed_paperclip gem.

Both of these gems exposes process_in_background to process the image upload to background. So my User model looks like:

class User < ActiveRecord::Base    # carrierwave    mount_uploader :cv_file, CvFileUploader    process_in_background :cv_file      # paperclip    has_attached_file :avatar,                       :default_url => "default-avatar.png",                      :styles => {                        :thumb => ['100x100#', :jpg, :quality => 80]                      }    process_in_background :avatar, processing_image_url: "default-avatar.png"      # ...    end  

I'm getting this error while trying to access any page on the app.

undefined method `remove_avatar?' for

Did you mean? remove_cv_file?

Any help will be greatly appreciated. Thank you!

LIKE query with MySQL always return nil

Posted: 23 Jan 2017 04:05 AM PST

First of all, I'm using rails 4.

What I'm trying to do is search some usernames in my MySQL database.

But whatever my query is, @search is nil, and the result is 404.

Here's my code.

I tried several changes with my params[:query] such as

"%#{params[:query]}%" or just params[:query] with out "%".

But it still didn't work

Any help will be appreciated.

def search_user          @searh=User.where('username LIKE ?', "%"+params[:query]+"%").all          if @search == nil               then              head 404, content_type: "text/html"              else              render json: @search.to_json, status: 200          end      end  

How do I count within nested resourced and display the results?

Posted: 23 Jan 2017 04:06 AM PST

I am building a job board in rails based on PostgreSQL. I want to count and display the amount of job offers per employer on the index of the employer page. What is the code for this kind of count?

I created a nested resource, and associated my employer and offer model, by:

class Employer < ActiveRecord::Base    has_many :offers, dependent: :delete_all  end  

Rails eager loading associations

Posted: 23 Jan 2017 04:14 AM PST

I have two models MSellingStaff and MPosition

#m_selling_staff.rb    class MSellingStaff < ActiveRecord::Base    belongs_to :m_position  end    #m_position.rb    class MPosition < ActiveRecord::Base    self.primary_key ='pos_id'    has_many :m_selling_staffs, :foreign_key => 'emp_pos_id'  end  

I have an attribute pos_short_name in m_position. When I try

@sellers = MSellingStaff.includes(:m_position).all  @sellers.first.pos_short_name  

I am getting

undefined method `pos_short_name' for #MSellingStaff:0x0000000651a5d0

and when I try

@sellers.first.m_position.pos_short_name  

I am getting

undefined method `pos_short_name' for nil:NilClass

In the rails console I can see that the SQL generated for

@sellers = MSellingStaff.includes(:m_position).all  

is

MSellingStaff Load (0.6ms) SELECT "m_selling_staffs".* FROM "m_selling_staffs" MPosition Load (0.2ms) SELECT "m_position".* FROM "m_position" WHERE "m_position"."pos_id" IN ('')

What am i doing wrong? thanks in advance

Developing API using Rails 5.x

Posted: 23 Jan 2017 03:30 AM PST

I need to develop a Rails based API which takes in a JSON input with parent and child data (Customer and his Cars), and stores them in User and Car tables respectively.

I am currently learning from Developing API using Rails 5

However, the above example uses two Controllers for each table. I need one single Transaction. Are there any resources to learn how to save in multiple tables in one block using Rails 5 API ?

Rails: build in certain order

Posted: 23 Jan 2017 03:12 AM PST

I create two addresses home address and semester using build, nested attributes and fields_for like below

 def new      @user.adresses.build(home_adress: true)      @user.adresses.build(semester_adress: true)   end     def edit      @user.adresses.build(home_adress: true) if @user.adresses.where(home_adress: true).blank?      @user.adresses.build(semester_adress = true) if @user.adresses.where(semester_adress: true).blank?   end  

and the form looks like this

 <%= f.fields_for :adresses do |builder| %>                <%= render 'adress', f: builder %>   <% end %>  

Now the problem is, if a user only add semester address, not home address during the registration, then when that user tries to edit the address, semester address shows first and then home address after that. But for me, the order is very important. So I have to show home address first even if it blank and then semester address. How can I do this?

Edit: I figured the above thing may not be clear. So here is another relevant example of what I need.

If I have a new action like this

   def new          @user.adresses.build(home_adress: true)          @user.adresses.build(semester_adress: true)     end  

and in the edit action I try to add more addresses as below

   def edit          @user.adresses.build(office_adress: true)          @user.adresses.build(parents_adress: true)          @user.adresses.build(home_adress: true)          @user.adresses.build(semester_adress: true)     end  

This does not build in order as I expect. Instead if a user home address and semester address build first since they are already in database and the new office and parents address build later since they are new builds. But I want them to build in the order. How can I do this?

JavaScript append Rails erb code

Posted: 23 Jan 2017 03:36 AM PST

I got a complicated select block which was written by rails erb, but now I need to rewrite it into jQury using append. The select block is like this

<select id="mission_reward" name="mission_reward" class="select_reward">    <option value="0"><%=t('mission.create_panel.no_reward')%></option>    <% @monsters.each do |monster|%>      <option data-img-src="<%=monster.url%>"              data-cost='<%=monster.need_q_point%>'              value="<%=monster.id%>">        <%= monster.name %>      </option>    <% end%>  </select>  

I've written some code following

html

<div class='select_block'></div>  <script type="text/javascript">    $(function() {      $('select_block').append(AppendReward());    });  </script>  

js

function AppendReward(){    return    "<select id=\"mission_reward\" name=\"mission_reward\" class=\"select_reward\"> \      <option value="0"><%=t('mission.create_panel.no_reward')%></option> \      <% @monsters.each do |monster|%> \        <option data-img-src="<%=monster.url%>" \              data-cost='<%=monster.need_q_point%>' \              value=\"<%=monster.id%>\"> \          <%= monster.name %> \        </option> \      <% end%> \    </select>"  }  

But it seems to fail, I am not familiar with JavaScript, is it wrong with the syntax?

Too may redirects rails respond_to

Posted: 23 Jan 2017 03:11 AM PST

I have a controller action method that gets all records of establishments from the DB, I then want to share this response with a external entity which is a RhoMobile application, i used respond_to to format the response to JSON.

def index    @establishments = Establishment.index(params).includes(:assessor)    @json_establishments = Establishment.all    respond_to do |format|      format.html { redirect_to(establishments_url) }      format.json { render json: @json_establishments.as_json }    end  end  

When i navigate to this action i get an error

net::ERR_TOO_MANY_REDIRECTS

in chrome developer tools on the console tab.

When i remove the { redirect_to(establishments_url) } next to the format.html it's working with a status of 406 (Not Acceptable) but if i would use the search in the action view that i created and click the browsers back button, i get something like:

ActionController::UnknownFormat in EstablishmentsController#index    ActionController::UnknownFormat  <div class="source hidden" id="frame-source-0">    <div class="info">      Extracted source (around line <strong>#219</strong>):    </div>  

instead and when i refresh the page i get the expected view.

JSONAPI testing with rspec and Airborne

Posted: 23 Jan 2017 02:56 AM PST

Hello i have problem with testing JSONAPI with rspec and airborne. GET model below https://i.stack.imgur.com/Cyf75.png

Im testing it this way https://i.stack.imgur.com/Y9rHt.png

Rspec output:

Failures: 1) GET on /contacts should validate types Failure/Error: expect_json('books.0', title: 'The Great Escape')

 Airborne::PathError:     Expected NilClass     to be an object with property 0   # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:21:in `rescue in block in get_by_path'   # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:18:in `block in get_by_path'   # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:9:in `each'   # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:9:in `each_with_index'   # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:9:in `get_by_path'   # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/request_expectations.rb:137:in `call_with_path'   # /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/request_expectations.rb:18:in `expect_json'   # ./book_resource.rb:10:in `block (2 levels) in <top (required)>'   # ------------------   # --- Caused by: ---   # NoMethodError:   #   undefined method `[]' for nil:NilClass   #   /home/robert/.rvm/gems/ruby-2.4.0/gems/airborne-0.2.5/lib/airborne/path_matcher.rb:57:in `process_json'  

Finished in 0.03121 seconds (files took 0.17681 seconds to load) 1 example, 1 failure

How to create force-directed graph of each individual area?

Posted: 23 Jan 2017 01:55 AM PST

I am fairly new to rails and to D3.js but have been working on creating forced-directed graphs. I would like to know if anyone can help me find a way to make force-directed graphs for individual 'areas' or 'groups'.

So for example, I have 6 groups of devices in a network, I am displaying these in one big graph (or topology) but I would like to also display each group individually as its own graph on separate pages.

This is as far as I have got but the @links section does not work as it should and I am stuck for ideas.

def group_1    @devices = Device.where("area = 'Group 1'")    @get_devices = @devices.map do |device|         {"id" => device.id, "name" => device.name, "group" => device.area }    end      @links = Link.where("from_device_id >== :from_id || to_device_id >= :to_id",                       {from_id:  @devices.id, to_id: @devices.id})    @get_links = @links.map do |link|     {"source" => link.from_device.id, "target" => link.to_device.id}    end      @all_data = { "nodes" => @get_devices, "links" => @get_links}    render json: @all_data    end  

This may be a stupid question, so I apologise but any help would be greatly appreciated.

Many Thanks

Faye

form_for > f.submit, How to only alert at update action.

Posted: 23 Jan 2017 01:35 AM PST

How would one set this up so it only pop's up at update action and not create?

= f.submit, data: { confirm: "you are about to update object, are you sure?" }

How to view rails/routes for a rails engine in the browser

Posted: 23 Jan 2017 02:32 AM PST

I have a rails engine, which is mounted in dummy/config/routes.rb using

mount Handicap::Engine => "/handicap"  

In the engine, I have a number of controllers, and when I start a rails server in the dummy directory these routes are active e.g. /handicap/tees/index responds. However, when I go to /rails/routes it only shows:

handicap_path       /handicap   Handicap::Engine  rails_routes_path   GET /rails/routes(.:format) sextant/routes#index  sextant_engine_path     /sextant    Sextant::Engine  

I can list them using rake routes, but my normal work flow is to list them in the browser. How do I list the engine routes in the browser?

No comments:

Post a Comment