Tuesday, January 24, 2017

Rails 4 + Simpleform + datetimepicker-rails How do I add a default time of 6:45pm | Fixed issues

Rails 4 + Simpleform + datetimepicker-rails How do I add a default time of 6:45pm | Fixed issues


Rails 4 + Simpleform + datetimepicker-rails How do I add a default time of 6:45pm

Posted: 24 Jan 2017 08:22 AM PST

Want to have a default time of 645pm in a form. I am using Rails 4 , Simple form & datepicker bootstrap gem.see image date Ok but want to change time to 45

= f.input :started_at, as: :string, class: 'form-control', input_html: { value: l(@happening.started_at, format: :date_time_picker), class: 'date_time_picker' }, label: "Start at"

I have tried a number of things including using default: '645' after the date_time_picker and reading the Simpleform documentation

How to delete a collection matching a condition

Posted: 24 Jan 2017 08:19 AM PST

I would like to delete all posts associated to every user of my application matching a determined condition. In particular I would like to delete all posts older than 30 days only if a user has more than 20 posts. At first I wrote the following code:

users = User.all  users.each do |user|      if user.posts.any? && user.posts.count > 20          user.posts.delete_all('created_at < ?', 30.days.ago)      end   end  

However, looking at the API documentation, method delete_all for collections does not imply the records are actually removed from the database, and that depends precisely on the specified parameter, :nullify or :delete_all

Therefore, considering that method delete_all for collections requires one of the above parameters, would the following code be correct:

users = User.all  users.each do |user|      if user.posts.any? && user.posts.count > 20          user.posts.where('created_at < ?', 30.days.ago).delete_all(:delete_all)      end   end  

or am I expected to use something different?

React on Rails - ! [remote rejected] master -> master (pre-receive hook declined)

Posted: 24 Jan 2017 08:18 AM PST

I'm working in rails 4.2.5, recently I have added react_on_rails in my app. I am getting an error when I try to push to heroku.

git push heroku master  Counting objects: 963, done.  Delta compression using up to 4 threads.  Compressing objects: 100% (793/793), done.  Writing objects: 100% (963/963), 982.20 KiB | 0 bytes/s, done.  Total 963 (delta 384), reused 160 (delta 70)  remote: Compressing source files... done.  remote: Building source:  remote:   remote: -----> Deleting 18 files matching .slugignore patterns.  remote: -----> Node.js app detected  remote: mkdir: cannot create directory '/tmp/build_2116c2c5be27b9852c9d716798b3bcf9/.heroku': Not a directory  remote:  !     Push rejected, failed to compile Node.js app.  remote:   remote:  !     Push failed  remote: Verifying deploy...  remote:   remote: !   Push rejected to acceptance.  remote:   To https://git.heroku.com/acceptance.git   ! [remote rejected] master -> master (pre-receive hook declined)  

Any help is much appreciated.

Rescuable after_commit callbacks (Rails 3)

Posted: 24 Jan 2017 08:06 AM PST

I have a model with several after_commit callbacks. In case any of the callbacks raises an exception, all others will be skipped.

I want to ensure that all callbacks are ran (even if one fails), without explicitly wrapping each of them with begin & rescue.

Is there a way to so? I've looked into rescuable option of CallbackChain but it doesn't seem to be stuiable for this case

class Order < ActiveRecord::Base      after_commit :a, :b        def a() 'in a' end      def b() puts 'in b'; fail 'Bad callback' end  end  

In this case, callback a will not run:

>> Order.create!  in b  [ERROR] Bad callback  

best practice : should i create a new controller or not ? in order to respect a good architecture

Posted: 24 Jan 2017 08:20 AM PST

I'm working on an application where both notifications and history are needed, and what makes it quite difficult is the fact that there is the notion of 'context'.

For example when the user is in a certain view, he must see only the notifications and the histories related to that context. There is a controller for each, but when I want to update the notifications in the client side ( live update using the Pusher ), from the server side I need to know the context where the user is. The solution put in place is to send an ajax request from the client side specifying the context he is in, with the route of course.

Now the question is, in order to respect a good architecture, since the ajax request sends the context which is used for both notification and history, should I create a controller to deal with that ( and then that controller will contact both controllers ) or should I use one of them?. Thanks

Ruby on Rails function for model attribute

Posted: 24 Jan 2017 08:09 AM PST

I have one active record model called Task with following attributes:

  • name (string)
  • due (date)
  • priority (int)

How do I create a function for priority so I can call it something like this

@task.priority.to_str would produce "Low", "High" based off the integer value

I don't want to override the attribute method to print out the string because I need to access the actual value.

How do you get a list from complex active record has_many involved from a subset of downstream objects

Posted: 24 Jan 2017 08:17 AM PST

I'm having a hard time getting a list of the leagues involved from a subset of games.

class League    has_many :teams    has_many :games, :through => :teams  end    class Team    belongs_to :league    has_many :home_games, :foreign_key => team_a_id, :source => :game    has_many :away_games, :foreign_key => team_b_id, :source => :game  end    class Game    belongs_to :home_team, :class_name => Team    belongs_to :away_team, :class_name => Team  end  

Data Examples:

AFC -         PATRIOTS -                    Home       Away                 G1(PATRIOTS vs DALLAS)              G2(PATRIOTS vs PITTSBURG)        PITTSBURG -               G2(PATRIOTS vs PITTSBURG)  NFC -         DALLAS -               G1(PATRIOTS vs DALLAS)              G3(DALLAS vs GREENBAY)              G4(DALLAS vs SEATTLE)        GREENBAY              G3(DALLAS vs GREENBAY)        SEATTLE              G4(DALLAS vs SEATTLE)  

Given a subset/collection of Game objects[G1,G4], is there a way to return the Leagues associated? (Return AFC & NFC)

Find all Games that have NFC teams [G1,G3,G4]

The challenge Im having with is the home_team / away_team seperation

thanks

How does one integrate Duo Mobile with Devise and Rails?

Posted: 24 Jan 2017 07:55 AM PST

The documentation for Duo's supported Ruby library is sparse. This question understandably mentions overriding Devise's session controller, but how? There does not seem to be a source for a clear explanation of how to integrate Duo with Devise. There is this gem, but it doesn't seem to be very active and I couldn't get it working. How do I do this?

Devise 401 Unauthorized

Posted: 24 Jan 2017 07:43 AM PST

I'm using Ruby 4.2.3 and Devise 4.2.0 and I'm trying to sign in using POST method ($resource AngularJS) but 'I'm getting 401 Enauthorized error ('You need to sign in or sign up before continuing')

I'm following this Documentation which is working fine if I try outside my app. For instance using 'Postman'.

Alright, some code:

My angular controller to send the log in data to server:

$scope.log_in = function(){          sendData = new Sign_in($scope.user);          sendData.$save(null, function(response){            $cookies.put("user_email", $scope.user.email);            $cookies.put("user_token", response.data.authentication_token);          }, function(error){              console.log('error log in');          });      }  

my session devise controller (as exactly as the tutorial)

class Users::SessionsController < Devise::SessionsController      def create      user = warden.authenticate!(auth_options)      token = Tiddle.create_and_return_token(user, request)          render json: { authentication_token: token }    end      def destroy      Tiddle.expire_token(current_user, request) if current_user        super      #render json: {}    end      private        # this is invoked before destroy and we have to override it      def verify_signed_out_user      end  end  

my postman example that shows that is working:

enter image description here

What am i missing? I try to look out all around but I couldn't find any updated info. Any guide you could recommend?

Thanks!

undefined method `permit' for "<p>tinymce</p>":String

Posted: 24 Jan 2017 07:56 AM PST

Im trying to implement tinyme gem and I get this error:

undefined method `permit` for "<p>tiny mce</p>":String  

This is the controller:

def note_params       params.require(:note).permit(:contact_id, :note)  end  

The View:

 <%= simple_form_for(@note) do |f| %>                    <%= f.error_notification %>                      <div class="form-group hidden-xs-up">                      <label><i class="fa fa-address-book-o" aria-hidden="true"></i> Contact</label>                      <%= f.select :contact_id, get_contact.collect{@contact.id},{}, class:"form-control" %>                    </div>                      <div class="form-group over-hide">                      <label><i class="fa fa-file-text-o" aria-hidden="true"></i> Note</label>                      <%= text_area_tag :note, "", :class => "form-control tinymce", :rows => 10, :cols => 60 %>                      <%= f.button :submit, class: "btn btn-info mt-2 float-sm-right" %>                    </div>                  <% end %>  

How should I fix this issue ?

Add autocomplete feature to rails app with selectize.js

Posted: 24 Jan 2017 07:34 AM PST

It's been two days that I'm fighting on a "simple" task. Adding an autocomplete field in a form on my rails application.

I'm running ruby 2.3.3 and rails 5.0.1. So far I've tried a bunch of different options such as: - Elasticsearch - Rails-jquery-autocomplete

Now I'm giving a go to selectize.js. I added the gem to my gemfile:

gem "selectize-rails"  

And I have included it in my application.js

//= require jquery  //= require jquery_ujs  //= require selectize  //= require turbolinks  //= require bootstrap-sprockets  //= require_tree .  //= require main  

I have created an action in my controller that returns the data from a table called Interests in a json format:

def users_interests_search      @interests = Interest.all      respond_to do |format|          format.js {}          format.json {render json: @interests}      end  end  

And in my script, I'm using the following (taken from here using the rottenTomato example):

$('.test-selectize').selectize({      valueField: 'title',      labelField: 'title',      searchField: 'title',      options: [],      create: false,      render: {          option: function(item, escape) {            return '<div>' +                        '<span class="title">' +                            '<span class="ciccioname">' + item.name + '</span>' +                        '</span>' +                    '</div>';          }      },      load: function(query, callback) {          if (!query.length) return callback();          $.ajax({              url: '/users-interests-search',              type: 'GET',              dataType: 'json',              success: function(res) {                  console.log(res);                  console.log(res[0].name)                  $('selectize-dropdown-content').append('<span class="ciccioname">' + res[0].name + '</span>')              }          });      }    });  

Although I do see the AJAX call made and the JSON returned, not much is going on on the actual page.

Any suggestion on the matter is the very welcome (or any other sort of help to get an autocomplete system up and running for that matter :) ).

Cheers! Andrea

Update: Here is the console output after changing the ajax call (see above)

Console screenshot

Rails: Serialization of custom class for flash messages

Posted: 24 Jan 2017 07:06 AM PST

I can't seem to figure out how flash messages in RoR insist on being serialized for the next page view. When setting a simple type to e.g. flash[:notice], all is well to get it across to the next page view. When I however try and set the value of flash[:notice] to a custom class, it serializes only the properties:

flash[:notice] = Info.notice("Content...", "Title")  

... equates to ...

{"type"=>"notice", "content"=>"Content...", "title"=>"Title"}  

... which has no knowledge of the class it serialized. One solution I found was to use .to_yaml before doing a redirect, and then use YAML.load at the later step, but I don't find that viable.

So my question is, how would I be able to make sure that it automatically serialize this object, to properly be deserialized at a later stage?

Rails: 4.2.5.1, Ruby: 2.2.4p230

Thanks

Rails + Devise ActionController::InvalidAuthenticityToken

Posted: 24 Jan 2017 07:03 AM PST

Cheers! I use Devise gem for authenticating users and locally (development env) I always get this ActionController::InvalidAuthenticityToken exception on devise::session/create action, no big deal I thought and added some dirt:

class ApplicationController < ActionController::Base    include EmailConcern   # Prevent CSRF attacks by raising an exception.   # For APIs, you may want to use :null_session instead.    protect_from_forgery with: :exception      before_action :authenticate_user!      def handle_unverified_request      true    end      ...    end  

All right, no more authenticity_token exceptions, I don't mind if it happens only in dev env. But! There is another problem - :authenticate_user! is never worked, so current_user is always nil and I always getting redirected with 401 unauthorized to new session path again. User's credentials are valid and user exists in the DB.

router.rb

Rails.application.routes.draw do    resources :coupons      devise_for :users, path: 'u'  

What could be the origin of this issue?

ruby-2.2.2@rails-4.2.0

Rails: load different modules for each environemnt

Posted: 24 Jan 2017 06:52 AM PST

I have rails application with two environments. Each environment has its own schema. How can configure rails to load specific modules for each environment?

e.g modules app/models/a.rb app/models/b.rb when running with environment X and app/models/c.rb app/models/d.rb when running with environment Y.

Sprockets::FileNotFound with jquery-ui-bootstrap

Posted: 24 Jan 2017 07:09 AM PST

Strange issue. Following the gem's docs I seem to be running into the error, Sprockets::FileNotFound in PostIndex:

couldn't find file 'ui-bootstrap/jquery-ui-bootstrap' with type 'text/css'  

Here is how I have my files setup:

Gemfile

gem 'jquery-rails'  gem 'twitter-bootstrap-rails'  gem 'jquery-ui-rails'  gem 'jquery-ui-bootstrap-rails'  

application.css

 *= require_tree .   *= require ui-bootstrap/jquery-ui-bootstrap   *= require jquery-ui   *= require_self  

application.js

//= require jquery  //= require jquery_ujs  //= require jquery-ui  //= require twitter/bootstrap  //= require turbolinks  //= require_tree .  

I'm using the latest versions of all of these gems.

Sunspot Solr fulltext search

Posted: 24 Jan 2017 06:17 AM PST

I'm having some trouble getting the right results in when searching my Issue model with Sunspot Solr.

Initially, I was doing a fuzzy search using ~ (tilde) but this is causing tons of unrelated items to show up.

I need to be able to search the problem and effected_versions fields in my DB:

In my Issue model:

class Issue < ActiveRecord::Base    searchable do      string :type      text :problem, :effected_versions    end  end   

And my initial search string was:

Issue.search { with :type, :cve; fulltext product.gsub(/\s|$/, "~ ") + version }.results  

This worked relatively fine, however any result that might have been 'close' to what the person was looking for was being returned. So, if the person searches for linux firmware:1 they were getting unrelated results along with related ones. Basically, anything that has the word "Linux" and "firmware:1" are being returned although in most cases they aren't related.

So, I've decided I need to do away with fuzzy search and get more specific. If someone searches I need only those specific results to return, based on what's in the product and effected_versions columns in my DB.

I was thinking about doing an exact phrase search, but I can't interpolate the variables that are being passed when doing this because of the double-quoting requirement. It just returns the literal string:

Issue.search{with :type, :cve; fulltext '"#{product} #{version}"'}.results  D, [2017-01-24T08:58:59.738474 #18849] DEBUG -- :   SOLR Request (4.1ms)  [ path=select parameters={fq: ["type:Issue", "type_s:cve"], q: ""#{product} #{version}"", fl: "* score", qf: "problem_text effected_versions_text", defType: "edismax", start: 0, rows: 30} ]  => []  

Is there a way around this so I can minimize incorrect results from showing?

Update

I found a way around the double-quoting requirement by wrapping my dynamic content in %{}, but now that's too restrictive.

Is there a happy medium?

Issue regarding cursor styling for a disabled button by javascript

Posted: 24 Jan 2017 06:45 AM PST

In my ruby on rails application I am using some javascript on one of my view page to make a submit button with id "submitorder" disabled. And I have done this successfully using the following line of code.

 $('#submitorder').prop('disabled', true);  

It is working fine.

But now I want to make the cursor as 'not-allowed' also when hovering on that submit button. That's why I have used the following lines of code to make the submit button disabled and as well as to make the cursor as 'not-allowed'

$('#submitorder').prop('disabled', true);  $('#submitorder').css( 'cursor', 'not-allowed' );  

But unfortunately the button becomes disabled only. There is no change in the cursor styling.

Please tell me why this is happening and give me clues to figure out this.

Thanks in advance!!

Mouse over to display more information using jquery with rails model

Posted: 24 Jan 2017 05:37 AM PST

I have 5 rows of 10 buttons arranged in a table. This represents a vending machine where there are 5 rows of 10 slots each. Each button displays basic information such as quantity of the items left in that slot. This is already done.

I want to allow mouse over the buttons to pop up a bigger window to show more information about each of the slot.These information must be retrieved from the vending machine model. It is not like popover where I just enter some static text. Here I have to query the db to display actual data.

html.erb

<% for i in item do %>               <% if !VendingMachine1.where(:slotID => i).first.nil? %>          <% vm = VendingMachine1.where(:slotID => i).first %>            <%= link_to  vending_machine1_path(vm.id),:class=>"vmButton",:method => :get do %>              <div class="myPara"><%= i %> </div>              <div class="myPara">Q:<%= find_vm_quantity(vm) %> </div>              <div class="myPara">P:<%= vm.priority %></div>              <div class="myPara"><%= vm.identifier %></div>            <% end %>          <% else %>              <div class="vmButton">              <div class="myPara"><%= i %> </div>              <div class="myPara">Q:-</div>              <div class="myPara">P:-</div>              <div class="myPara">-</div>              </div>          <% end %>        <% end %>  

any suggestions on how I could achieve that? thank you.

Ruby Object mutations within sidekiq workers

Posted: 24 Jan 2017 07:41 AM PST

I have a wrapper that sends user updates to an external service, on a regular basis, running inside a Sidekiq worker. Each User has its own Sidekiq Job. Sidekiq is setup to use 20 threads. It's a Rails 5.0.1 app, MRI Ruby 2.3.0. Webserver is Passenger 5 Community.

If I over simplify, the code looks like this:

class ProviderUserUpdateJob < ApplicationJob    queue_as :default      def perform(user_id)      user = User.find(user_id)      Provider::User.new(user).push_update    end  end      class Provider::User       def initialize(user)      @user = user    end      def push_update      SomeApiWrapper.call(        user_id: @user.id,        status: @user.status      )    end      ....  end  

Now, the BIG problem that I only have on production and I finally catched up by looking at the logs can be summarized like this :

class Provider::User       def initialize(user)      @user = user    end      def push_update      SomeApiWrapper.call(        user_id: @user.id,    # Some user        status: @user.status  # NOT THE SAME USER !!! (and I have no idea where he is coming from)      )    end      ....  end  

2 Questions:

  1. How it this even possible? Does it comes from Provider::User being by essence a globally accessible object, so, from threads to threads, everything gets mixed up in a mutating soup?!

  2. If I only use "functional" style, without any instance, passing parameters and outputs from static methods to static methods, can it solve my problem or am I completely wrong? How can I fix this?

Ultimately, is there any way to really battle test this kind of code so I can be sure not to mix users data?

truncate and restart identity of a set of tables

Posted: 24 Jan 2017 05:44 AM PST

My application uses Postgresql.
I would need to remove all rows from a set of tables (table1 to table4) and restart the id with one command from a rb file.

In the Postgresql documentation I found that TRUNCATE with RESTART IDENTITY would do the job as follows:

TRUNCATE table1, table2, table3, table4 RESTART IDENTITY;  

According to How to restart id counting on a table in PostgreSQL after deleting some previous data? at Stackoverflow, I can use the following command:

ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name RESTART IDENTITY")  

So putting together the two documentations, would it be correct to use the following command:

ActiveRecord::Base.connection.execute("TRUNCATE table1, table2, table3, table4 RESTART IDENTITY")  

considering that in the API dock documentation the connection method is reported as deprecated or moved?.

how to display one controller show action in another controller action in rails

Posted: 24 Jan 2017 05:17 AM PST

I am using two controller incident and incident_list, i am displaying all incidents in incident_list/index page when click on show button in each incident i want to display that incident details

IncidentListController

def show     @incidents = Incident.all     @incident = Incident.find(params[:id])     render "incidents/show"   end  

IncidentController

def show    @incidents = Incident.all    @incident = Incident.find(params[:id])   end  

incidnet_lists/index.html.erb

<table>    <table class="table table-striped table-bordered">     <thead >    <tr>        <th class="c2">Case ID</th>        <th class="c2">Call Type</th>        <th class="c2">Number of People</th>        <th class="c2"></th>      </tr>   </thead>  <tbody>    <tr>      <td><%= inc.id %> </td>      <td><%= inc.call_type %> </td>      <td><%= inc.no_of_people %></td>      <td><%= link_to 'Show', @incidents %></td>      </tr>   </tbody>  </table>   

incidents/show.html.erb

 <table class="table table-striped table-bordered">     <thead>       <tr>         <td class= "c2" > Case Id </td>         <td class= "c2"> Caller Name </td>         <td class="c2"> Contact Number </td>         <td class= "c2"> Calling For </td>         <td class="c2"> Call Type </td>        <tr>        </thead>       <tbody>         <% @incidents.each do |inc| %>         <tr>           <td> <%= inc.id %> </td>           <td> <%= inc.caller_name %></td>           <td> <%= inc.contact_number %></td>           <td> <%= inc.for_whom %> </td>           <td> <%= inc.call_type %> </td>         </tr>         <% end %>       </tbody>     </table>  

when click on show button in the incident_list page incident show page should be display

Rails: Change Status Onclick

Posted: 24 Jan 2017 04:56 AM PST

enter image description here

I have the following where I am monitoring a job status. What I would like to do is be able to click each div and have a menu appear where I can change the status. Is this possible?

PDFKit Unknown long argument --root-url

Posted: 24 Jan 2017 05:55 AM PST

I'am trying to use the :root_url parameter with PDFKit like suggested here https://github.com/pdfkit/pdfkit in Resolving relative URLs and protocols section:

PDFKit.new(html, root_url: 'http://example.com/').to_file  

My code:

html = Nokogiri::HTML(open("http://stackoverflow.com"))  PDFKit.new(html.to_s, root_url:'http://stackoverflow.com/').to_file(file.path)  

returns wkhtmltopdf error Unknown long argument --root-url. Does anyone know how can I resolve this?

versions: wkhtmltopdf 0.12.4 pdfkit 0.8.2 tested also with wkhtmltopdf 0.12.3 pdfkit 0.8.0

RSpec before in a helper

Posted: 24 Jan 2017 04:38 AM PST

Is it possible to do something like this?

module MyHelper    before (:each) do      allow(Class).to receive(:method).and_return(true)    end  end  

Then in my tests I could do something like:

RSpec.describe 'My cool test' do    include MyHelper    it 'Tests a Class Method' do      expect { Class.method }.to eq true    end  end  

EDIT: This produces the following error:

undefined method `before' for MyHelper:Module (NoMethodError)  

Essentially I have a case where many tests do different things, but a common model across off of them reacts on an after_commit which ends up always calling a method which talks to an API. I dont want to GLOBALLY allow Class to receive :method as, sometimes, I need to define it myself for special cases... but I'd like to not have to repeat my allow/receive/and_return and instead wrap it in a common helper...

Have username instead of id then nested route /users/:id/nest_routes to /username/nested_routes

Posted: 24 Jan 2017 03:42 AM PST

Hello i have heaps of routes such as the following

  resources :users do      resources :shipping_methods, only: [:new, :create, :edit, :update, :destroy]      resources :cart_items, only: [:create, :index, :destroy]      resources :relationships, only: [:create, :destroy]      resources :addresses, only: [:new, :create, :edit, :update, :destroy]    end  

They all produce the following route

/users/:id/nested_route

For instance an edit shipping method view produces the following

/users/1/shipping_methods/11/edit

How do i make all these routes produce this:

/username/nested_route

For example the edit shipping method view above should produce the following:

/username/shipping_methods/11/edit

ruby on rails error config_check.rb:87:in `initialize':

Posted: 24 Jan 2017 03:43 AM PST

I have just installed ruby on rails and can not figure out whats wrong with it whenever I run it gives the following error:

# Rails Environment Configuration.  The system cannot find the file specified.  The system cannot find the file specified.  C:/RailsInstaller/scripts/config_check.rb:87:in `initialize': No such file or directory @ rb_sysopen - C:\Users\HP/.ssh/id_rsa.pub (Errno::ENOENT)          from C:/RailsInstaller/scripts/config_check.rb:87:in `open'          from C:/RailsInstaller/scripts/config_check.rb:87:in `<main>'    C:\Sites>  

Testing a belongs_to relationship in Rails with rspec

Posted: 24 Jan 2017 02:51 AM PST

I have a model called Page that has many Paragraphs. This all works but I thought it was about time I had some tests. For reasons, I need a count of all the paragraphs a page has, +1 so I know how to number the next paragraph. I do this with a count_paragraphs method in my model:

class Page < ApplicationRecord    has_many :paragraphs      def count_paragraphs      paragraphs.count + 1    end  end  

So far so simple. This works fine in my controller, where I use it to create the next paragraph.

@paragraph = @page.paragraphs.create(body: para_params[:body], num: @page.count_paragraphs)  

As mentioned this all works. But in testing, this does not work:

it 'has a paragraph count of 1' do      expect(subject.count_paragraphs).to eq 1  end    it 'successfully counts paragraphs' do    subject.paragraphs.new(body: "hello", num: 1)    expect(subject.count_paragraphs).to eq 2  end  

The first test passes, the second does not. It always returns 1. When I binding.pry the test, each new paragraph shows up if I do subject.paragraphs but if I binding.pry in the model, paragraphs just comes back []. So I am misunderstanding something about the model relationship.

Does anyone have any idea what I'm doing wrong here?

Rails bootstrap color depending on value

Posted: 24 Jan 2017 05:03 AM PST

Project.status can be [1,2,3]. Is there a better way of defining the following logic (color depends on status), than doing it in the view?

- if project.status == '1'    %td.bg-success= project.status  - elsif project.status == '2'    %td.bg-warning= project.status  - else    %td.bg-danger= project.status  

Double has_many attributes

Posted: 24 Jan 2017 07:49 AM PST

I'm beginner in rails and having trouble finding a proper way out with my problem.

I have three models : Conversation, participant, messages which have the following attributes :

Conversation :

module Messenger    class Conversation <ActiveRecord::Base        has_many :participants, :class_name => 'Messenger::Participant'        def messages        self.participants.messages.order(:created_at)      end    end  end  

Participant :

module Messenger      class Participant <ActiveRecord::Base        has_many :messages, :class_name => 'Messenger::Message'        belongs_to :conversation, :class_name => 'Messenger::Conversation'      end  end  

Message :

module Messenger      class Message <ActiveRecord::Base        default_scope {order(:created_at)}      default_scope {where(deleted: false)}        belongs_to :participant, :class_name => 'Messenger::Participant'      end  end  

My trouble is that I'm trying to make a single form to create a conversation with a first message in it. The form looks like this :

= form_for @conversation, url: messenger.conversations_create_path do |f|    .row      .col-md-12.no-padding        .whitebg.padding15          .form-group.user-info-block.required            = f.label :title, t('trad'), class: 'control-label'            = f.text_field :title, class: 'form-control'            .form-group.user-info-block.required            = f.label :model, t('trad'), class: 'control-label'            = f.text_field :model, class: 'form-control'            .form-group.user-info-block.required            = f.label :model_id, t('trad'), class: 'control-label'            = f.text_field :model_id, class: 'form-control'            = fields_for @message, @conversation.participants.message do |m|            = m.label :content, t('trad'), class: 'control-label'            = m.text_area :content, class:'form-control'      .user-info-block.action-buttons      = f.submit t('trad'), :class => 'btn btn-primary pull-right'  

I've tried many ways to make this form simple but I've encountered some problems which I don't know how to fix using rails properly.

I've tried using Field_forto include a message in my conversation form, but since I have nothing saved in my database yet it seems I can't link a message to an unexisting participant.

So basically I want my first form, once validated, to create a conversation, link the current user to that conversation and link the message to that first user, but I assume there are ways to do it with the framework and I would not like to do it manually.

What is the proper way to follow to achieve that? Am I even on the good track or shoould I change something or add something?

Edit : to make it more understandable, a participant got a user_id and a conversation_id, which means this is a relation table. I can't adapt the attributes of my models to make it easier since I must keep it in that way for security reasons.

Extract Data from Excel Spreadsheet into Database in Ruby

Posted: 24 Jan 2017 02:47 AM PST

I'm looking to extract quite a lot of data from spreadsheets for a Rails application, but I'm doing the extraction through the Rails Console.

I have a table called instititutes in my database which currently has around 170 records. I've found far better data in a spreadsheet with c.1000 records and want to import that to my database, but to skip any records that match already.

I thought that using the find_or_create_by method would be the best move for this. The spreadsheet has UKPRN and NAME as headers, and the table has ukprn and name as respective columns (as well as others).

Using the Roo gem, I've got this so far:

require 'roo'    xlsx = Roo::Spreadsheet.open(File.expand_path('../Downloads/UKPRN.xlsx'))  xlsx.default_sheet = xlsx.sheets.last  header = xlsx.row(1)  xlsx.each_row do |row|      row = Institute.find_or_create_by(UKPRN: ukprn , NAME: name)  end  

This is giving the error NameError: unitialized constant UKPRN. I'm still getting my head back into Ruby so any help would be appreciated.

I'm using Ruby 2.2.3 and Rails 5.0.1

Edit:

p row shows:

["UKPRN", "NAME"]  [10000291, "Anglia Ruskin University"]  [10000385, "The Arts University Bournemouth"]  [10000571, "Bath Spa University"]  [10000712, "University College Birmingham"]  [10000824, "Bournemouth University"]  [10000886, "The University of Brighton"]  [10000961, "Brunel University London"]  ...etc  

No comments:

Post a Comment