Saturday, April 9, 2016

How do I implement sending a task to another user so he can get crud ability for it? | Fixed issues

How do I implement sending a task to another user so he can get crud ability for it? | Fixed issues


How do I implement sending a task to another user so he can get crud ability for it?

Posted: 09 Apr 2016 07:30 AM PDT

I am working on the Task Manager app. How do I implement a functionality to share my task with another user in the system so he can get full crud ability for it?

extend a model ActiveRecord with Postgresql

Posted: 09 Apr 2016 06:43 AM PDT

I am trying to extend a ActiveRecord this class. I am using Postgresql

class Jobo::Provider < ActiveRecord::Base    self.abstract_class = true  end  class Jobo::Stripe < Provider  # code  end  

When i am trying to add

self.abstract_class = true

I have got this error

2.2.2 :001 > Jobo::Provider.first TypeError: no implicit conversion of nil into String from /Users/Michelin/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/utils.rb:24:in `quote_ident' from /Users/Michelin/.rvm/

Where is my error?

Can't map JSON data to model

Posted: 09 Apr 2016 06:36 AM PDT

Currently trying to call an API and map an attribute to my model. e.g. image_src string from the JSON response to image string in my model. But right now It's getting the error 'no implicit conversion of String into Integer'.

Feed.rb

require 'httparty'  require 'json'    class Feed < ActiveRecord::Base    include HTTParty    base_uri 'https://extraction.import.io/query/runtime'    has_many :entries      # GET /feeds    # GET /feeds.json      def fetch_data        response = self.class.get("/2365205f-8502-439e-a6d2-73988cfa03f1?&url=http%3A%2F%2F%2F")      @elements = response.parsed_response["extractorData"]        @elements.map do |image_info|        self.entries.create(image: image_info['url'])      end      end  end  

Entry.rb

class Entry < ActiveRecord::Base    belongs_to :feed  end  

HTML

<% @feed.entries.each do |image| %>    <div class="grid-item">      <%= image_tag(image) %>    </div>  <% end %>  

JSON Response

{    "extractorData": {      "url": "http://linxspiration.com/",      "resourceId": "e26012fd5f25602c1c4e0945a7507e1f",      "data": [        {          "group": [            {              "image": [                {                  "src": "http://40.media.tumblr.com/0a38dd25a41e0702940c084b60bee860/tumblr_o5c0tyGhOP1qkegsbo1_1280.jpg",                  "href": "http://linxspiration.com/post/142509606341"                }              ]            },            {              "image": [                {                  "src": "http://36.media.tumblr.com/276def9e46bdfb9efee7f7d4e4444195/tumblr_o5c0szx4F21qkegsbo1_1280.jpg",                  "href": "http://linxspiration.com/post/142506402604"                }              ]            },            {              "image": [                {                  "src": "http://40.media.tumblr.com/4953cdecc24389d94844dfb88c819d8c/tumblr_o055uh8b7h1uhpqwfo1_1280.jpg",                  "href": "http://linxspiration.com/post/142503176501/linxsupply-discipline-gets-shit-done-buy-this"                }              ]            },            {              "image": [                {                  "src": "http://41.media.tumblr.com/353f10283fc3a0237262629b6a395c90/tumblr_o5aadrw6l31qkegsbo1_1280.jpg",                  "href": "http://linxspiration.com/post/142499072059"                }              ]            },            {              "image": [                {                  "src": "http://40.media.tumblr.com/889c65a662a1b690f299593e3581b947/tumblr_o57uysuSjF1tq9q5vo1_1280.jpg",                  "href": "http://linxspiration.com/post/142493659142/blazepress-sunrise-in-venice"                }              ]            },            {              "image": [                {                  "src": "http://45.media.tumblr.com/14c24e549a6559b48933f05ff40e3627/tumblr_o57vmsJ7gk1tq9q5vo1_400.gif",                  "href": "http://linxspiration.com/post/142488060049/blazepress-i-lick-paw"                }              ]            },            {              "image": [                {                  "src": "http://36.media.tumblr.com/f184f397d14563c9e41136c5fe370016/tumblr_o59oo0pUy61qkegsbo1_1280.jpg",                  "href": "http://linxspiration.com/post/142476686818"                }              ]            },            {              "image": [                {                  "src": "http://40.media.tumblr.com/453b70fd4055952e907766a5942cc560/tumblr_o59ohsGHBo1qkegsbo1_1280.jpg",                  "href": "http://linxspiration.com/post/142470776914"                }              ]            },            {              "image": [                {                  "src": "http://41.media.tumblr.com/1de6c873de55ddb899f83441454ff5bb/tumblr_o59ohhnd0k1qkegsbo1_1280.jpg",                  "href": "http://linxspiration.com/post/142465333421"                }              ]            },            {              "image": [                {                  "src": "http://40.media.tumblr.com/f71b3ee53f51a9679dc65096933f2b08/tumblr_o59of8kouq1qkegsbo1_1280.jpg",                  "href": "http://linxspiration.com/post/142456009994"                }              ]            },            {              "image": [                {                  "src": "http://40.media.tumblr.com/b6aa0dc78619a6b9e09b232224c0bfb7/tumblr_o59oeu18Ly1qkegsbo1_1280.jpg",                  "href": "http://linxspiration.com/post/142452801623"                }              ]            },            {              "image": [                {                  "src": "http://41.media.tumblr.com/d1c5a23af31880d10fd89fc8a6a0b8e6/tumblr_o585z3mPuF1tq9q5vo1_1280.jpg",                  "href": "http://linxspiration.com/post/142449893982/blazepress-life"                }              ]            },            {              "image": [                {                  "src": "http://41.media.tumblr.com/03369de74399e12e1901b3751917c512/tumblr_o54gbfJlXx1qkegsbo1_1280.jpg",                  "href": "http://linxspiration.com/post/142445969058"                }              ]            },            {              "image": [                {                  "src": "http://40.media.tumblr.com/6543cbb31ea206a59cbdd1e865d63562/tumblr_o54mncUOEP1qkegsbo1_1280.jpg",                  "href": "http://linxspiration.com/post/142440337822"                }              ]            }          ]        }      ]    },    "pageData": {      "statusCode": 200,      "timestamp": 1460206655245    }  }  

Any help would be brilliant!

Update columns from a CSV

Posted: 09 Apr 2016 06:57 AM PDT

I have the following code which is supposed to update each row in my Rental model with the attributes from each row of the CSV file. The row with an ID of 1 in the database should have its attributes updated with the values of line 1 in the CSV etc... I have 10000 rows in table and 10000(excluding header) in CSV.

However instead of updating the attributes in the model where id = row it is updating all row attributes in table with the first row of CSV, then the second etc...

Any help would be appreciated!

csv_text = File.read(Rails.root.join('db', 'Lpostcodes.csv'))  csv = CSV.parse(csv_text, :headers => true)  csv.each do |row|    postcode = row['postcode']    latitude = row['latitude']    longitude = row['longitude']    puts $INPUT_LINE_NUMBER    #update a particular row    Rental.update($INPUT_LINE_NUMBER, postcode: postcode, latitude: latitude,             longitude: longitude)  end  

How to handle multiple layout in Rails

Posted: 09 Apr 2016 06:56 AM PDT

we have lots of panel in out Application like admin , teacher principal , student , parent etc .

Each panel have its own layout So upon login we handle this using WelcomeController

class WelcomeController < ApplicationController    def index      respond_to do |format|        format.html do          return render :home if current_user.nil?          return render :admin if current_user.super?          return redirect_to("/student/lesson") if current_user.student?          return redirect_to("/teacher/lesson") if current_user.teacher?          return render "layouts/principal" if current_user.principal?          return render "layouts/coordinator" if current_user.coordinator?          return render "layouts/viceprincipal" if current_user.viceprincipal?          return render "layouts/parent" if current_user.parent?        end      end    end  end  

So right now for getting data from controller we redirect to his route Like for Student

return redirect_to("/student/lesson") if current_user.student?  

but we wants that on URL / we get data from controller . So my problem is how to get data ? So we can use in views

I am new to Rails , if I am using something wrong Please let me know . Will I get data from Model ?

In routes we use

get '/student/lesson', to: 'student_lesson_plan#index', as: 'student_lesson'  

And from index Action we have variables which we use . So I want instead of

return redirect_to("/student/lesson") if current_user.student? something like this

return render "layouts/student" if current_user.student?  

And I can use those variables which I initialize in student_lesson_plan#index or from another place

Internal Server Error in 1ms (ActiveRecord: 0.0ms) ArgumentError (wrong number of arguments (2 for 1)):

Posted: 09 Apr 2016 05:55 AM PDT

I have two devise models- Student and Teacher. All of my Rspec tests are passing, which must go through the sign up/sign in process. The thing is, the exact same code works on a friend's computer, however, when I run the rails server on my machine, and try to access the teacher sign in form by going to http://localhost:3000/teachers/sign_in, I get this stack trace in my terminal:

ArgumentError in Devise::SessionsController#new  wrong number of arguments (2 for 1)    Here is my full stack trace from the terminal:    Started GET "/teachers/sign_in" for ::1 at 2016-04-09 13:39:11 +0100  Processing by Devise::SessionsController#new as HTML  Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)    ArgumentError (wrong number of arguments (2 for 1)):    devise (3.5.6) lib/devise.rb:464:in `[]'    devise (3.5.6) lib/devise.rb:464:in `block (2 levels) in configure_warden!'    warden (1.2.6) lib/warden/session_serializer.rb:34:in `fetch'    warden (1.2.6) lib/warden/proxy.rb:212:in `user'    warden (1.2.6) lib/warden/proxy.rb:322:in `_perform_authentication'    warden (1.2.6) lib/warden/proxy.rb:104:in `authenticate'    warden (1.2.6) lib/warden/proxy.rb:114:in `authenticate?'    devise (3.5.6) app/controllers/devise_controller.rb:103:in `require_no_authentication'    activesupport (4.2.5) lib/active_support/callbacks.rb:432:in `block in make_lambda'    activesupport (4.2.5) lib/active_support/callbacks.rb:145:in `call'    activesupport (4.2.5) lib/active_support/callbacks.rb:145:in `block in halting_and_conditional'    activesupport (4.2.5) lib/active_support/callbacks.rb:504:in `call'    activesupport (4.2.5) lib/active_support/callbacks.rb:504:in `block in call'    activesupport (4.2.5) lib/active_support/callbacks.rb:504:in `each'    activesupport (4.2.5) lib/active_support/callbacks.rb:504:in `call'    activesupport (4.2.5) lib/active_support/callbacks.rb:92:in `__run_callbacks__'    activesupport (4.2.5) lib/active_support/callbacks.rb:778:in `_run_process_action_callbacks'    activesupport (4.2.5) lib/active_support/callbacks.rb:81:in `run_callbacks'    actionpack (4.2.5) lib/abstract_controller/callbacks.rb:19:in `process_action'    actionpack (4.2.5) lib/action_controller/metal/rescue.rb:29:in `process_action'    actionpack (4.2.5) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'    activesupport (4.2.5) lib/active_support/notifications.rb:164:in `block in instrument'    activesupport (4.2.5) lib/active_support/notifications/instrumenter.rb:20:in `instrument'    activesupport (4.2.5) lib/active_support/notifications.rb:164:in `instrument'    actionpack (4.2.5) lib/action_controller/metal/instrumentation.rb:30:in `process_action'    actionpack (4.2.5) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'    activerecord (4.2.5) lib/active_record/railties/controller_runtime.rb:18:in `process_action'    actionpack (4.2.5) lib/abstract_controller/base.rb:137:in `process'    actionview (4.2.5) lib/action_view/rendering.rb:30:in `process'    actionpack (4.2.5) lib/action_controller/metal.rb:196:in `dispatch'    actionpack (4.2.5) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'    actionpack (4.2.5) lib/action_controller/metal.rb:237:in `block in action'    actionpack (4.2.5) lib/action_dispatch/routing/route_set.rb:76:in `call'    actionpack (4.2.5) lib/action_dispatch/routing/route_set.rb:76:in `dispatch'    actionpack (4.2.5) lib/action_dispatch/routing/route_set.rb:45:in `serve'    actionpack (4.2.5) lib/action_dispatch/routing/mapper.rb:49:in `serve'    actionpack (4.2.5) lib/action_dispatch/journey/router.rb:43:in `block in serve'    actionpack (4.2.5) lib/action_dispatch/journey/router.rb:30:in `each'    actionpack (4.2.5) lib/action_dispatch/journey/router.rb:30:in `serve'    actionpack (4.2.5) lib/action_dispatch/routing/route_set.rb:817:in `call'    warden (1.2.6) lib/warden/manager.rb:35:in `block in call'    warden (1.2.6) lib/warden/manager.rb:34:in `catch'    warden (1.2.6) lib/warden/manager.rb:34:in `call'    rack (1.6.4) lib/rack/etag.rb:24:in `call'    rack (1.6.4) lib/rack/conditionalget.rb:25:in `call'    rack (1.6.4) lib/rack/head.rb:13:in `call'    actionpack (4.2.5) lib/action_dispatch/middleware/params_parser.rb:27:in `call'    actionpack (4.2.5) lib/action_dispatch/middleware/flash.rb:260:in `call'    rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'    rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'    actionpack (4.2.5) lib/action_dispatch/middleware/cookies.rb:560:in `call'    activerecord (4.2.5) lib/active_record/query_cache.rb:36:in `call'    activerecord (4.2.5) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'    activerecord (4.2.5) lib/active_record/migration.rb:377:in `call'    actionpack (4.2.5) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'    activesupport (4.2.5) lib/active_support/callbacks.rb:88:in `__run_callbacks__'    activesupport (4.2.5) lib/active_support/callbacks.rb:778:in `_run_call_callbacks'    activesupport (4.2.5) lib/active_support/callbacks.rb:81:in `run_callbacks'    actionpack (4.2.5) lib/action_dispatch/middleware/callbacks.rb:27:in `call'    actionpack (4.2.5) lib/action_dispatch/middleware/reloader.rb:73:in `call'    actionpack (4.2.5) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'    actionpack (4.2.5) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'    web-console (2.3.0) lib/web_console/middleware.rb:28:in `block in call'    web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch'    web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'    actionpack (4.2.5) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'    railties (4.2.5) lib/rails/rack/logger.rb:38:in `call_app'    railties (4.2.5) lib/rails/rack/logger.rb:20:in `block in call'    activesupport (4.2.5) lib/active_support/tagged_logging.rb:68:in `block in tagged'    activesupport (4.2.5) lib/active_support/tagged_logging.rb:26:in `tagged'    activesupport (4.2.5) lib/active_support/tagged_logging.rb:68:in `tagged'    railties (4.2.5) lib/rails/rack/logger.rb:20:in `call'    actionpack (4.2.5) lib/action_dispatch/middleware/request_id.rb:21:in `call'    rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'    rack (1.6.4) lib/rack/runtime.rb:18:in `call'    activesupport (4.2.5) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'    rack (1.6.4) lib/rack/lock.rb:17:in `call'    actionpack (4.2.5) lib/action_dispatch/middleware/static.rb:116:in `call'    rack (1.6.4) lib/rack/sendfile.rb:113:in `call'    railties (4.2.5) lib/rails/engine.rb:518:in `call'    railties (4.2.5) lib/rails/application.rb:165:in `call'    rack (1.6.4) lib/rack/lock.rb:17:in `call'    rack (1.6.4) lib/rack/content_length.rb:15:in `call'    rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'    /Users/charlieperson/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'    /Users/charlieperson/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'    /Users/charlieperson/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'        Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_source.erb (3.8ms)    Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.7ms)    Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.8ms)    Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (45.7ms)    Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.6ms)    Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.2ms)    Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.3ms)    Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.3ms)    Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (40.8ms)    Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.2ms)    Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.3ms)    Rendered /Users/charlieperson/.rvm/gems/ruby-2.2.3/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (90.3ms)  

The devise sign up/sign in form does show up correctly when I go to http://localhost:3000/students/sign_in but once I click log in I get this error:

ArgumentError in DashboardController#index wrong number of arguments (2 for 1)

def index @student = current_student @teacher = current_teacher (It doesn't like this line) end

Essentially, it refuses to recognize or let me use the devise helper methods. Any help would be greatly appreciated. If this is not clear enough, please let me know. I searched for an answer for a very long time, tried many proposed solutions, without any luck.

Pdf kit custom font not working

Posted: 09 Apr 2016 05:31 AM PDT

I tried get custom font in pdfdit but not working:

@font-face { font-family: 'oswald_regularregular'; src: url(file://#{Rails.root.join('app', 'assets', 'fonts', 'oswald-regular.ttf')}) format('truetype'); }

how to automatically publish the post on my app facebook page using rails

Posted: 09 Apr 2016 05:59 AM PDT

I have a blogging application in Ruby on Rails.

I want to publish all the blogs which are published on my rails application to my facebook page automatically from background jobs.

I explore the Facebook Graph Api Feed Api and do some hit and try but didn't get any success.

So could anyone please suggest that how I achieve that.

Thanks in advance.

Rails form_for sending params to controller action and not model

Posted: 09 Apr 2016 05:36 AM PDT

In the controller review_queue I have a custom action that posts a result to a target URL, I want to build a form for this action. I am not going to save any of the fields to the DB I am just going to pass them in the params to the post_review action.

def post_review    RestClient::Request.execute(:method => :post,                                :url => Rails.application.secrets['target_url'],                                :content_type => :json,                                :payload => @result_params.merge!(params[:reasons]).to_json,                                :headers => HEADERS)  end  

In the view I have a form that will be filled out and on submit it should send up the reasons when the form is submited, I am setting the review_queue_id and the status in the form, since these are static, but the reasons should come from the textarea

<%= form_for(:review_queue, url: { action: 'post_review', :review_queue_id => @review_queue.id, :status => 'accepted'} ) do |f| %>    <div class='form-group'>      <label for='comment'>Please give a reason? (required)</label>      <%= f.text_area(:reasons, placeholder: 'Your commentns ...', rows: 9, class: 'form-control') %>    </div>    <div class='modal-footer'>      <%= f.submit 'Approve', class: 'btn btn-success btn-decission btn-modal-left-side'  %>      <button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>    </div>  <% end %>  

error message:

NoMethodError - undefined method `reasons' for #<ReviewQueueApplication:0x007fa7ff7832d8>:  

It seems as if rails is assuming the MVC architecture here, and assuming I want to pass the reasons to the review_queue model. there is no reasons column so it's dropping a no method error. Is there a way of specifying that the form is 'temporary' and only getting as far as the controller?

This seems like it should be a simple thing but there is some rails magic happening here.

App for managing apps (architecture)

Posted: 09 Apr 2016 05:14 AM PDT

I know it's gonna be a very broad question and I'm pretty sure this is not anything new in todays world, but I really don't now where to start on this one.

I've started working on a rails-based service that would allow users to create, configure and manage their projects (basicaly copies of a single app with customization). The projects would be run on a subdomain with an option of connecting their own domain. (Quite similar to how SquareSpace and Wix and many other website building services handle their websites)

I want these projects to be as flexible and customizable as possible (including the visual design, some additional features etc) while maintaing ease of setup and updates for the codebase itself.

So the questions I start with:

  1. Should each project be a separate app (basicaly a copy out of the same repo) with its own configs, database, nginx and unicorn configs, etc. or should I keep all in 1 app and differenciate them with different configs and maybe databases and assets?
  2. If it's better to keep everything separated...
    1. ... what's the best setup process (provided that I have basic configuration to start with)?
    2. ... how would I be able to update them all (with bugfixes, new features, performance improvements etc.) from one place?
  3. If I keep all the projects in the same app...
    1. ... how should I manage the configuration concurency between projects?
    2. ... how do I separate the data and assets?

As always, I'd be grateful for any sufficient help I can get.

Rails 4.2.6 - has_many through, undefined method 'name' do nil:NilClass (ruby 2.3.0, fails only on production)

Posted: 09 Apr 2016 05:08 AM PDT

I have prototype model

class ArchMagazine::Prototype < ActiveRecord::Base    self.table_name = 'arch_magazine_prototypes'      has_many :custom_dictionaries, through: :dictionaries_prototypes, source: :custom_dictionary, foreign_key: :custom_dictionary_id    has_many :dictionaries_prototypes, -> { where(kind: 'normal') }, dependent: :destroy, class_name: 'ArchMagazine::DictionariesPrototype'  end  

and service

class ArchMagazine::UpdatePrototype < ArchMagazine::PrototypeCore      def process      if prototype_form.valid?        prototype.update(prototype_form.prototype_attrs)        add_custom_dictionaries(prototype, true)      else        raise ValidationError.new      end    end      def add_custom_dictionaries(prototype, with_destroy = false)      prototype.custom_dictionaries.destroy_all if with_destroy      prototype_form.custom_dictionary_ids.present? and prototype_form.custom_dictionary_ids.each do |dictionary_id|        create_record(prototype, dictionary_id, 'normal')      end    end    end  

When I'm trying to update prototype object (creating works fine) with some new custom_dictionaries_ids, application fails at

prototype.custom_dictionaries.destroy_all if with_destroy

Error link (not exactly mine but same active_record error): http://pastebin.com/TZugtfrd

Funny thing is that code from my example works on development just fine. Production is the problem. Some time before, development would run on ruby 2.0.0-p195, rails 4.0.4 and everything were fine. Then I updated ruby version on production to 2.3 and applications started to fail. Situation repeats itself on development when I updated ruby on this environment. After that I updated rails on development to 4.2.6 and everything started to run smoothly. But nothing changes on production after deploying updated rails line in Gemfile.

Rails has_many :through validation nested records count by specific param

Posted: 09 Apr 2016 06:19 AM PDT

I have models Workout and User which related as many to many through model UserWorkout. And model UserWorkout has attribute :is_creator, which show what user was the creator. But Workout should have only one creator. What is the best way to add such validation?

 class Workout < ActiveRecord::Base      has_many :user_workouts, inverse_of: :workout, dependent: :destroy    has_many :participants, through: :user_workouts, source: :user      def creator      participants.where(user_workouts: { is_creator: true }).order('user_workouts.created_at ASC').first    end    end    class UserWorkout < ActiveRecord::Base      belongs_to :user    belongs_to :workout    end    class User < ActiveRecord::Base      has_many :user_workouts, inverse_of: :user, dependent: :destroy    has_many :workouts, through: :user_workouts    end  

Was partial replacement were removed in Turbolinks 5

Posted: 09 Apr 2016 04:22 AM PDT

I am wondering if Turbolinks 5 has partial replacement as in 3rd version. Also where is the 3rd version, is it Turbolinks-classic? At the rubygems site I can find only 2.5 and 5th version listed. In turbolinks-classic documentation I see partial replacement documentation which says for versions (3+). So I lost where is the Turbolinks 3, or is it just now called Turbolinks 5? Sorry if my question is unclear.

How do I write an ActiveRecord query that filters out results from a joined table?

Posted: 09 Apr 2016 07:11 AM PDT

Users and Sessions are joined by a has_and_belongs_to_many association.

How do I get the list of Users that meet the following conditions?

  • user.coach == true
  • user.available == true

And then NOT include any results where that user is a coach in an active Session:

  • session.coach_id == user.id
  • session.call_ends_at == nil

Is there a way I can write this with ActiveRecord Query language? Do I need to write a pure SQL statement? Some kind of hybrid? What would YOU do?

I also have scopes and associations defined that could be helpful here. But I'm not sure how to add them in:

  • User.available_coaches (scope)
  • Session.in_progress (scope)
  • user.sessions_available_for (association)
  • session.available_coaches (association)

User model

class User < ActiveRecord::Base    has_many :client_sessions, class_name: 'Session', foreign_key: :client_id    has_many :coach_sessions, class_name: 'Session', foreign_key: :coach_id    has_and_belongs_to_many :sessions_available_for, class_name: 'Session',                            join_table: 'available_coaches'      scope :coaches, -> { where(coach: true) }    scope :available_coaches, -> { coaches.where(available: true) }  

Session model

class Session < ActiveRecord::Base    belongs_to :client, class_name: 'User'    belongs_to :coach, class_name: 'User'    has_and_belongs_to_many :available_coaches,                            -> { order(:first_name, :last_name) },                            class_name: 'User', join_table: 'available_coaches'      scope :in_progress, -> { where.not(coach: nil).where(call_ends_at: nil) }  

Schema

  create_table "available_coaches", id: false, force: :cascade do |t|      t.integer "session_id"      t.integer "user_id"    end      add_index "available_coaches", ["session_id"], name: "index_available_coaches_on_session_id", using: :btree    add_index "available_coaches", ["user_id"], name: "index_available_coaches_on_user_id", using: :btree      create_table "sessions", force: :cascade do |t|      t.integer  "client_id"      t.integer  "coach_id"      t.boolean  "canceled",          default: false      t.datetime "coach_accepted_at"      t.datetime "call_begins_at"      t.datetime "call_ends_at"      t.datetime "created_at",                        null: false      t.datetime "updated_at",                        null: false    end      add_index "sessions", ["client_id"], name: "index_sessions_on_client_id", using: :btree    add_index "sessions", ["coach_id"], name: "index_sessions_on_coach_id", using: :btree      create_table "users", force: :cascade do |t|      t.string   "first_name"      t.string   "last_name"      t.boolean  "coach",             default: false      t.boolean  "available",         default: false      t.datetime "created_at",                        null: false      t.datetime "updated_at",                        null: false    end  

response.body in Rspec controller test returns an empty string

Posted: 09 Apr 2016 04:15 AM PDT

I'm trying to build a restful JSON api in Rails using the Devise gem and I have the following code:

users_controller_spec.rb:

require 'rails_helper'    RSpec.describe Api::V1::UsersController, type: :controller do        describe "PUT/PATCH #update" do      render_views      context "when is successfully updated" do          before(:each) do          @user = FactoryGirl.create :user          request.headers['Authorization'] = @user.auth_token        end          it "renders the json representation for the updated user" do          user_response = json_response          expect(user_response[:email]).to eq "newmail@example.com"        end    end  end  

The issue I have is that response.body equals an empty string, which isn't valid JSON and hence I can't do JSON.parse(response.body)

I read elsewhere on SO to include render_views and you can see I've done that, but it makes no difference.

Please let me know if you need more info

Ruby on rails "add to cart paypal"

Posted: 09 Apr 2016 03:54 AM PDT

Whats the best way to set up a "Add to cart" system using paypal. I have to do this using ruby on rails and do it through c9. I already have the basic html and css done and have the add to cart icon under all the images

ROR: How to get and compare just the dates of datetimes using SQL query

Posted: 09 Apr 2016 04:03 AM PDT

I want to be able to list any 'events' in my database which occur on the same date as another event being creating in my method. The column I want to compare is 'starts_at' and is a DateTime. How can I just compare the date that events occured on instead of both date and time?

I need to add the query to this where call:

events = Event.where(location_id: location.id)  

I already have a date object date to compare to, I just don't know how I can get just the date part of the events already in the database?

is it something along the lines of date(starts_at:)?

events = Event.where(location_id: location.id, date(starts_at:): date)  

I am using sqlite database.

Mixing GlobalID::Identification for form object

Posted: 09 Apr 2016 03:17 AM PDT

Rails 4.2.5

I have Form object Feedback.

class Feedback    include ActiveModel::Model    attr_accessor :name, :message      validates :name, :message, presence: true  end  

And controller FeedbacksController

  def create      @feedback = Feedback.new(feedback_params)      if @feedback.valid?        FeedbackServiceMailer.new_feedback(@feedback).deliver_later        redirect_to root_url, notice: 'Thanks for your feedback!'      else        render :index, status: 400      end    end  

To be able to pass @feedback object to Mailer. I have added GlobalID::Identification mixin and provided id and self.find methods:

  def id      object_id    end      def self.find(id)      ObjectSpace._id2ref(id.to_i)    end  

My question, is it okay to provide object_id for deserializing Form object?

As I understood Ruby GC will not collect @feedback object if something have a reference to it.

Ruby on Rails - On click event to "link_to"

Posted: 09 Apr 2016 03:07 AM PDT

The goal here is that once a user clicks on a "link_to" button, that a ruby method will execute but I am unclear as to how I am to do that.

Here is my link to call within my .html.erb file:

<%= link_to image_tag(@artist.related_artists[1], class: 'artist_show_related'), artist_path(@artist.related_artists[0]) %>  

Is there are way to cause this to also run a ruby method once clicked?

buildpacks in cloud foundry

Posted: 09 Apr 2016 03:27 AM PDT

Folks, can I ask about buildpacks, specifically ruby vs java buildpack for a rails jruby application.

I believe we currently use a java buildpack, but could we use a ruby buildpack instead and are there any advantages in doing so for a rails jruby app?

Java Buildpack Version: v3.5.1  | https://github.com/cloudfoundry/java-buildpack.git#3abc3db  

Our web server is tomcat, but I assume this would need to change to puma for example.

Expanding Tomcat Instance to .java-buildpack/tomcat   

How would I specify the ruby build pack instead of the Java one?>

Handling Price & Currency in rails app

Posted: 09 Apr 2016 03:01 AM PDT

I'm following this tutorial http://pauldeardorff.com/2013/08/14/handling-currencies-in-ruby-on-rails-apps/ about adding a price and currency selection in a rails app.

In a starter app I have my modules set up exactly like the simple tutorial

My problem seems to arrive when I first render a new action for my product class. The tutorial advises to create a money_attributes file within the rails Lib folder.

    # lib/money_attributes.rb       module MoneyAttributes       extend ActiveSupport::Concern       module ClassMethods        def money_attributes *args             args.each do |attribute|       cents_attribute = "#{attribute}_in_cents"         define_method attribute do         send(cents_attribute).try("/", 100.0)         end        define_method "#{attribute}=" do |value|         value.gsub!(/[^\d.]/,"") if value.is_a? String                    send("#{cents_attribute}=", value.try(:to_f).try("*", 100))       end        define_method "#{attribute}_money" do                                        Money.new(send("#{attribute}_in_cents").to_f || 0,send("currency")).format         end        attr_accessible attribute if accessible_attributes.include?(cents_attribute)    end  end   end   end  

My app spits out undefined local variable or method `accessible_attributes'.

I have an Idea of what's wrong because the 'accessible_attributes' was discontinued in rails 4 I believe. My issue is I have no idea how I would fix this method. Also my control strong parameters looks as following

     products_controller.rb  

...... private

    def product_params        params.require(:product).permit(:price, :currency)      end   

If anyone has an idea on how to fix this I'll greatly appreciate it or might have a better method in mind that matches the tutorial. My issue is that I would like the price and currency selection separate within my models form. just like specified within this tutorial. Any help would be greatly appreciated.

After pushing to heroku, page is blank even if source code isn't

Posted: 09 Apr 2016 04:38 AM PDT

After dealing with a problem where heroku rejected to push because of assets rejection (When deploying heroku app I get push rejected error (Precompiling assets failed)), solution was this command: RAILS_ENV=production bundle exec rake assets:precompile.

Now my app is finally pushed to heroku and there is no longer default message on the app URL, however page is now blank.

This is my Gemfile:

source 'https://rubygems.org'    gem 'rails', '4.2.2'    gem 'sass-rails', '~> 5.0'    gem 'uglifier', '>= 1.3.0'    gem 'jquery-rails'    gem 'turbolinks'    gem 'jbuilder', '~> 2.0'    gem 'sdoc', '~> 0.4.0', group: :doc  # rake  gem 'rake', '11.1.2'  # csv reader  gem 'smarter_csv'  # bower rails  gem 'bower-rails'  # angular templates  gem 'angular-rails-templates'  # angular material  gem 'rails-angular-material'  # jquery ui  gem 'jquery-ui-rails'  # ionicons  gem 'ionicons-rails'  # Get user location info  gem 'geocoder'    group :development, :test do    gem 'byebug'    gem 'sqlite3'  end      gem 'spring'    group :development do    gem 'web-console', '~> 2.0'  end    group :test do    gem 'minitest-reporters', '1.0.5'    gem 'mini_backtrace',     '0.1.3'    gem 'guard-minitest',     '2.3.1'  end    group :production do    gem 'pg'    gem 'rails_12factor'  end    ruby "2.2.1"  

And this is my Bowerfile:

asset 'angular'  asset 'angular-route'  asset 'angular-material'  

On the screenshot there are 3 windows, source code from heroku app, heroku app (blank page) and same app on localhost. Whole file structure can be seen here: https://github.com/kunokdev/flightmap because I really don't know which part could cause this problem. How do I fix this to properly show my web page?

enter image description here

There were no errors in console when I was pushing it, however this line caught my eye:

 remote:        Detected manifest file, assuming assets were compiled locally  

The whole console log can be found here: https://jpst.it/GTtq

Agular + Rails beginner's questions

Posted: 09 Apr 2016 05:10 AM PDT

I'm learning angular for last two weeks. I think it's really interesting to work with frontend framework, I don't have expected that I'll have to create 2 separate complete apps :). I've some questions on you

  1. what is the best method to manage models connections in angular like rails user.animals.where(...)

e.g. I have User model, every user has many animals. On the page I want to show link table with Users animals and right table with all animals, now I make two promises to animals controller once for users and once for all animals, it's double the queries number and is hard to manage when I want add a form for create a new animal, because i have to push new object into two models arrays in angular

further when every animal could have many toys and user can add only one toy pro animal of another user it becomes to be really complicated

I have to send json from rails controller and includes animals toys and also an array with users ids, then in view

ng-hide="(animal['users_ids'].includes(user.id)"   

with this solution, when I create a new model I have to update toys model and also animals, could it be done simpler?

  1. What is the best method to sync angular and rails model when the latter changes?

I could refresh page every x second, but it's not pro.

  1. I've confirugred rails and angular to works with devise and oauth. My configurations works but I'm not sure if the solution is solid and safe

    Gemfile   gem 'devise'  gem 'omniauth-facebook'  gem 'omniauth-github'  gem 'angular_rails_csrf'  

rails generate devise:install

set up existing User model

    devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebook, :github]        def self.from_omniauth(auth)        where(provider: auth.provider, uid: auth.uid).first_or_create do |user|          user.provider = auth.provider          user.uid = auth.uid          user.email = auth.info.email          user.password = Devise.friendly_token[0,20]        end      end  

set up devise initializers

    config.clean_up_csrf_token_on_authentication = true  

set up onniauth initializers

    Rails.application.config.middleware.use OmniAuth::Builder do        provider :facebook, ENV['APP_ID'], ENV['APP_SECRET'],          scope: 'email,public_profile', info_fields: 'email,id,name'      end  

set up routes

    devise_for :users,  :controllers => { :omniauth_callbacks => "sessions#create" }      get '/auth/:provider/callback', to: 'sessions#create'  

sessions controller

      def facebook          @account = User.from_omniauth(request.env["omniauth.auth"])          sign_in @account          render 'sessions/create', layout: false        end          def github          @account = User.from_omniauth(request.env["omniauth.auth"])          sign_in @account          render 'sessions/create', layout: false        end  

app/views/sessions/create.html.erb

    <p>This view will now self-destruct</p>      <script>         try {            window.opener.$windowScope.handlePopupAuthentication('<%= @provider %>', <%= @account.to_json.html_safe %>);         } catch(err) {}         window.close();      </script>  

and angular configuration

app/assets/templates/login.html.slim

    div.page-header        h1 Log In        div class="btn dash-subs login-btn" ng-click="authNetwork('facebook')"        p Login With Facebook  

app/assets/javascript/auth/authCtrl.js

    angular.module('myAPP')        .controller('AuthCtrl', [        '$scope',        '$state',        'Auth',        function($scope, $state, Auth){           $scope.handlePopupAuthentication = function handlePopupAuthentication(network, account) {            $scope.$apply(function(){              window.location.reload()            });         }           $scope.authNetwork = function authNetwork(network) {            var openUrl = '/users/auth/' + network            window.$windowScope = $scope;            window.open(openUrl, "Authenticate Account", "width=500, height=500");         };      }])  

Is .create method adding nil value if it fails to recognize an integer in Rails 4

Posted: 09 Apr 2016 12:51 AM PDT

In my controller, I need to pluck a single, matching integer value and then create a record with that value in another table. In action, it looks like this:

  if Participation.where(ranking: "1")        first = PointsAllocation.where(game_id: params[:game_id]).where(place: "1").pluck(:points)        Stack.create(game_id: params[:game_id], user_id: current_user.id, chips: first)      else        end   

I have tested in the console that the first variable is definable. If I run PointsAllocation.where(game_id: "1").where(place: "1").pluck(:points), it will return:

SELECT "points_allocations"."points" FROM "points_allocations" WHERE "points_allocations"."game_id" = 1 AND "points_allocations"."place" = 1 => [10]

Ok, so it is correctly plucking what looks like an integer value for Points. I then want to use this points value and send it to the Chips column in the Stack table. When I run this, it will add a nil record even though first is defined, like so:

<Stack id: 1, game_id: 1, user_id: 1, chips: nil>

In troubleshooting, I thought maybe the issue here is that even though it looks like an integer (and Chips, I should add, is a t.integer attribute), maybe it's accidentally a string or something from pluck. So let's map this to an integer to be safe by adding map(&:to_i) after the pluck.

When I do that, it gets weirder, as it now returns:

<Stack id: 9, game_id: 1, user_id: 1, chips: 0>

So when I convert it to an integer, it changes 10 to a 0 and adds it to the table.

Where am I going wrong?

AJAX Image Upload with React, Rails and Paperclip

Posted: 09 Apr 2016 01:46 AM PDT

Been searching but nothing comes close to my question, except this php question.

In my react component, using Rails 5, I could upload an image to S3 only if I submit the form; I don't want to refresh the page so I thought I could simply use ajax for that:

...    imageUpload(){    var formData = $(this).serialize();     $.ajax({         url: '<url>',         type: 'POST',         data: formData,         async: false,         cache: false,         contentType: false,         processData: false,         success: function (data) {             console.log(data);         },         error: function () {             alert("error in ajax form submission");         }     });  },    ...  

The html:

<form encType="multipart/form-data" acceptCharset="UTF-8">    <input      type="file"      name="user[evidence]"      id="user_evidence"    />    <button className="success button small" onClick={this.imageUpload}>Upload</button>  </form>  

The goes to the update method (ajax url finds the method no problem):

...    def update   u = User.find(1)   u.update_attributes(user_evidence) # causing ajax to return an error  end    private    def user_evidence     params.require(:user).permit(:evidence)    end  

When an image is added and button is clicked, nothing uploads to s3. I guess I'm missing some sort of remote information with the ajax?

Ruby on Rails - Setting different names for url

Posted: 09 Apr 2016 12:43 AM PDT

I am completely new to Rails and I have a database that links to a certain page depending on the user's search but it will always give me the id.

For example if a user searches, I will get, "localhost:3000/fruit/1" instead of "localhost:3000/fruit/apple". Does anyone know how to switch the url from an id to name?

TypeError in AlbumPhotosController#create no implicit conversion of nil into String

Posted: 09 Apr 2016 01:30 AM PDT

I am creating the app of gallery that stores the photos as well as albums in it. I took help from the following site: Multiple image upload with carrierwave

But I am facing the error of

TypeError in AlbumPhotosController#create no implicit conversion of nil into String

This is my code for controller:

def create  @album_photo = AlbumPhoto.new(album_photo_params)    respond_to do |format|    if @album_photo.save      format.html { redirect_to @album_photo, notice: 'Album photo was successfully created.' }      format.json { render :show, status: :created, location: @album_photo }    else      format.html { render :new }      format.json { render json: @album_photo.errors, status: :unprocessable_entity }    end  end  end    def album_photo_params    params.require(:album_photo).permit(:album_id,{albumphotos: []})  end  

This is my Model:

#AlbumPhoto Model  class AlbumPhoto < ActiveRecord::Base    belongs_to :album    mount_uploader :albumphotos, AlbumphotoUploader  end    #Album Model  class Album < ActiveRecord::Base    belongs_to :gallery    has_many :album_photos  end  

This is my view:

 <%= form_for(@album_photo) do |f| %>      <div class="field">        <%= f.file_field :albumphotos, multiple: true %>      </div>      <div class="actions">      <%= f.submit %>    </div>  <% end %>  

How to send automated email in ruby on rails using whenever gem

Posted: 08 Apr 2016 11:23 PM PDT

i'm making a project in rails where i want to add automated email functionality.I choosed whenever gem for that purpose.I created rake task separately for sending email.

email_tasks.rake

desc 'send digest email'  task send_digest_email: :environment do    # ... set options if any     InterviewScheduleMailer.sample_email(@interview_schedule).deliver!  end  

schedule file

set :environment, :development  # Example:  #  # set :output, "/path/to/my/cron_log.log"  #   every :friday, :at => '3:52 am' do      rake 'send_digest_email'  end    every :friday, :at => '4:01 pm' do       runner "InterviewSchedule.sample_email"   end  

my email only goes when i run bundle exec send_digest_email.

i want the email to be delivered to all the employees based on date.For example who is having birthday.So email should go automatically at 12 a.m.

Add Dashing Gem dashboard to existing rails app?

Posted: 08 Apr 2016 10:56 PM PDT

I have a rails app I've been developing on the Cloud 9 IDE. I've been looking for the best solution for a user dashboard once someone authenticates to Devise. Dashing looks awesome.

How do I install the gem and create a new dashboard, without having to create a whole new rails project? I can't have two apps running in the same c9 workspace, so I need to create a new dashboard in my existing application so I can connect to my db, etc... right?

Thanks for any help.

devise error: Log in : Invalid email or password

Posted: 09 Apr 2016 12:14 AM PDT

This is the bug:

Started GET "/javascripts/vendor/custom.modernizr.js" for ::1 at 2016-04-09 12:42:41 +0800    ActionController::RoutingError (No route matches [GET] "/javascripts/vendor/custom.modernizr.js"):    actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'    web-console (2.3.0) lib/web_console/middleware.rb:28:in `block in call'    web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch'    web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'  

I create a user index about some user base info.

class UsersController < ApplicationController    before_action :set_user    before_action :owned_user, only: [:edit, :update]          def index        @user = User.all    end      def edit      @user = User.find_by(name: params[:name])    end      def update      if @user.update(user_params)          flash[:success] = 'Your profile has been updated.'          redirect_to user_path(@user.name)      else          @user.errors.full_messages          flash[:error] = @user.errors.full_messages          render :edit      end    end            private      def user_params      params.require(:user).permit(:name, :email, :password, :avatar)    end      def owned_user      unless current_user == @user          flash[:alert] = "That profile doesn't belong to you!"          redirect_to root_path      end    end      def set_user      @user = User.find_by(name: params[:name])    end         end      class User < ActiveRecord::Base    mount_uploader :avatar, AvatarUploader    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable      validates :name, presence: true, length: { minimum: 4, maximum: 16 }    end  

about views/devise , I have not change anything. This is my routes.rb

Rails.application.routes.draw do    resources :topics    devise_for :users    resources :nodes      root 'topics#index'      get ':name', to: 'users#index', as: :users    get ':name/edit', to: 'users#edit', as: :edit_user    patch ':name/edit', to: 'users#update', as: :update_user    end  

This is routes:

 new_user_session GET    /users/sign_in(.:format)       devise/sessions#new          user_session POST   /users/sign_in(.:format)    devise/sessions#create  destroy_user_session DELETE /users/sign_out(.:format)  devise/sessions#destroy         user_password POST   /users/password(.:format)  devise/passwords#create     new_user_password GET    /users/password/new(.:format) devise/passwords#new    edit_user_password GET   /users/password/edit(.:format)devise/passwords#edit                       PATCH  /users/password(.:format)  devise/passwords#update                       PUT    /users/password(.:format)  devise/passwords#update  cancel_user_registration GET    /users/cancel(.:format)devise/registrations#cancel     user_registration POST   /users(.:format)       devise/registrations#create     new_user_registration GET    /users/sign_up(.:format) devise/registrations#new    edit_user_registration GET    /users/edit(.:format)   devise/registrations#edit                       PATCH  /users(.:format)       devise/registrations#update                       PUT    /users(.:format)       devise/registrations#update                       DELETE /users(.:format)      devise/registrations#destroy                   users GET    /:name(.:format)               users#index             edit_user GET    /:name/edit(.:format)          users#edit           update_user PATCH  /:name/edit(.:format)          users#update  

Thank you to help me , I am tired to solve devise. I am new , expect devise, Is there any Gem better to login/logout?

No comments:

Post a Comment