Saturday, January 21, 2017

Rails Admin: display a has many association with checkboxes | Fixed issues

Rails Admin: display a has many association with checkboxes | Fixed issues


Rails Admin: display a has many association with checkboxes

Posted: 21 Jan 2017 07:44 AM PST

Rails Admin displays the has_many association as a couple of boxes like this:

rails admin selector

Instead, I would like to show simple checkboxes.

How can I achieve that?

How to know plain text of :encrypted_password, in devise?

Posted: 21 Jan 2017 07:30 AM PST

If i use has_secure_password, i have whitelist are: password, password_confirmation, and password_digest. With password is the plain text of password_digest, which was encrypted by bcrypt.

But when i use devise with my user model, it has only encrypted_password field, I don't know how to know plain text of password. The schema doesn't has password field. I uasually use rails consle to debug. So anyone can help me how to know the plain text of encrypted_password.

gem pg destroyed my app

Posted: 21 Jan 2017 07:01 AM PST

UserXs-MacBook-Pro:shobiz Ayaz$ rails s  => Booting Puma  => Rails 5.0.1 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  Exiting  /Users/userx/.rvm/gems/ruby-2.3.0/gems/puma-3.6.2/lib/puma/launcher.rb:328:in `stat': No such file or directory @ rb_file_s_stat - /Users/userx/Desktop/shobiz (Errno::ENOENT)      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/puma-3.6.2/lib/puma/launcher.rb:328:in `generate_restart_data'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/puma-3.6.2/lib/puma/launcher.rb:66:in `initialize'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/puma-3.6.2/lib/rack/handler/puma.rb:47:in `new'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/puma-3.6.2/lib/rack/handler/puma.rb:47:in `run'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/server.rb:296:in `start'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/server.rb:79:in `start'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:90:in `block in server'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:85:in `tap'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:85:in `server'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>'      from /Users/userx/Desktop/showbiz/bin/rails:9:in `require'      from /Users/userx/Desktop/showbiz/bin/rails:9:in `<top (required)>'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `load'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `call'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/command.rb:7:in `call'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client.rb:30:in `run'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/bin/spring:49:in `<top (required)>'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `load'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `<top (required)>'      from /Users/userx/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /Users/userx/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /Users/userx/Desktop/showbiz/bin/spring:14:in `<top (required)>'      from bin/rails:3:in `load'      from bin/rails:3:in `<main>'  

It was my first time to upload app on heroku I have installed gem pg. but now unable to run rails server and getting these type error

Rails delayed job and docker: adding more workers

Posted: 21 Jan 2017 06:57 AM PST

I run my rails app using a Docker. Now delayed jobs are processed by a single worker that runs in a separate contariner called worker and it runs with a command bundle exec rake jobs:work.

I have several types of jobs that I would move to a separate queue and create a separate worker for that or at least have two workers for process tasks. I tested run my worker container with env QUEUE=default_queue bundle exec rake job:work && env QUEUE=another_queue bundle exec rake job:work bit that do not make any sense. It does not fails, is starts but jobs aren't processed. Is there any way to have separate workers in one container? And is it correct? Or should I create separate container for each worker I would ever want to make?

Thanx in advance!

Redmine : rake aborted due to "existent table "when installing "wk-time" Plugin

Posted: 21 Jan 2017 06:34 AM PST

I'm trying to install the "ERPmine" plugin :

Official documentation : http://www.redmine.org/plugins/wk-time

As the documentation says , and like every plugin i'm used to do the following :

  1. importing this pugin to the /redmine/plugins
    (successfull)
  2. running: bundle install (successfull)
  3. updating the schema of the database by running this : (aborted)

    rake redmine:plugins:migrate NAME=redmine_wktime RAILS_ENV=production

the error syas that there is a tbale which is already created "Table 'wk_addresses' already exists"

there is some blogs which talked on updating the DB , by executing this :

rake db:migrate RAILS_ENV=production  

but the plugin set up still failing ; the complete error is that :

== 5 CreateWkBilling: migrating ===============================================  -- create_table(:wk_addresses)  rake aborted!  StandardError: An error has occurred, all later migrations canceled:    Mysql2::Error: Table 'wk_addresses' already exists: CREATE TABLE `wk_addresses` (`id` int(11) auto_increment PRIMARY KEY, `address1` varchar(255), `address2` varchar(255), `work_phone` varchar(255), `home_phone` varchar(255), `mobile` varchar(255), `email` varchar(255), `fax` varchar(255), `city` varchar(255), `country` varchar(255), `state` varchar(255), `pin` int(11), `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL) ENGINE=InnoDB  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `_query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `block in query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `handle_interrupt'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `query'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `block in execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:484:in `block in log'  /var/lib/gems/2.1.0/gems/activesupport-4.2.7.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:478:in `log'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/mysql2_adapter.rb:231:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/schema_statements.rb:222:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:474:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:665:in `block in method_missing'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `block in say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:654:in `method_missing'  /opt/redmine/plugins/redmine_wktime/db/migrate/005_create_wk_billing.rb:3:in `change'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:608:in `exec_migration'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:591:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:590:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:768:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:1046:in `ddl_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:997:in `execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:959:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `each'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:823:in `up'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:801:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:481:in `migrate_plugin'  /opt/redmine/lib/redmine/plugin.rb:453:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:464:in `migrate'  /opt/redmine/lib/tasks/redmine.rake:127:in `block (3 levels) in <top (required)>'  /var/lib/gems/2.1.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'  ActiveRecord::StatementInvalid: Mysql2::Error: Table 'wk_addresses' already exists: CREATE TABLE `wk_addresses` (`id` int(11) auto_increment PRIMARY KEY, `address1` varchar(255), `address2` varchar(255), `work_phone` varchar(255), `home_phone` varchar(255), `mobile` varchar(255), `email` varchar(255), `fax` varchar(255), `city` varchar(255), `country` varchar(255), `state` varchar(255), `pin` int(11), `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL) ENGINE=InnoDB  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `_query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `block in query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `handle_interrupt'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `query'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `block in execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:484:in `block in log'  /var/lib/gems/2.1.0/gems/activesupport-4.2.7.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:478:in `log'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/mysql2_adapter.rb:231:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/schema_statements.rb:222:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:474:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:665:in `block in method_missing'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `block in say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:654:in `method_missing'  /opt/redmine/plugins/redmine_wktime/db/migrate/005_create_wk_billing.rb:3:in `change'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:608:in `exec_migration'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:591:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:590:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:768:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:1046:in `ddl_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:997:in `execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:959:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `each'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:823:in `up'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:801:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:481:in `migrate_plugin'  /opt/redmine/lib/redmine/plugin.rb:453:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:464:in `migrate'  /opt/redmine/lib/tasks/redmine.rake:127:in `block (3 levels) in <top (required)>'  /var/lib/gems/2.1.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'  Mysql2::Error: Table 'wk_addresses' already exists  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `_query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `block in query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `handle_interrupt'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `query'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `block in execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:484:in `block in log'  /var/lib/gems/2.1.0/gems/activesupport-4.2.7.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:478:in `log'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/mysql2_adapter.rb:231:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/schema_statements.rb:222:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:474:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:665:in `block in method_missing'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `block in say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:654:in `method_missing'  /opt/redmine/plugins/redmine_wktime/db/migrate/005_create_wk_billing.rb:3:in `change'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:608:in `exec_migration'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:591:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:590:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:768:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:1046:in `ddl_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:997:in `execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:959:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `each'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:823:in `up'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:801:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:481:in `migrate_plugin'  /opt/redmine/lib/redmine/plugin.rb:453:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:464:in `migrate'  /opt/redmine/lib/tasks/redmine.rake:127:in `block (3 levels) in <top (required)>'  /var/lib/gems/2.1.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'  Tasks: TOP => redmine:plugins:migrate  (See full trace by running task with --trace)  

Any suggestions ??

Redmine - 501 Syntactically invalid HELO argument(s)

Posted: 21 Jan 2017 06:00 AM PST

Installed redmine on remote server(ubuntu)

In redmine i want test mail(Setting-email notification). Get error:

An error occurred while sending mail (501 Syntactically invalid HELO argument(s) )

I have following setting mail:

config/configuration.yml

default:    email_delivery:      delivery_method: :smtp      smtp_settings:        address: "mail.name.com"        port: 25        authentication: :login        domain: 'xxx.xx.xx.xx:81'        user_name: 'office@mail.com'        password: 'xxxxxxxx'        enable_starttls_auto: false        openssl_verify_mode: 'none'  

etc/hosts

127.0.0.1       localhost h997VM  xxx.xx.xx.xxx   ubuntu14gi    # The following lines are desirable for IPv6 capable hosts  ::1     localhost ip6-localhost ip6-loopback  ff02::1 ip6-allnodes  ff02::2 ip6-allrouters  

etc/hostname

h997VM  

Information about system:

Ubuntu 14  Environment:    Redmine version                3.3.2.devel    Ruby version                   2.3.1-p112 (2016-04-26) [x86_64-linux]    Rails version                  4.2.7.1    Environment                    production    Database adapter               PostgreSQL  

What could be the reason? An how fix? Thank for advance for your help.

Using Wikipedia-Client Gem to Update Rails Database

Posted: 21 Jan 2017 05:53 AM PST

My ruby and Rails is a bit rusty. I have a table in my database called institutes which has some of the columns filled. I want to use the Wikipedia-Client gem to fill some of the others. I want to use the name attribute to find the page on Wikipedia then use page.summary for the description attribute in my table and page.image_urls.first for the picture attribute. At the moment, I'm struggling to work out how I would go about this.

My current code is:

require 'Wikipedia'  Institute.each do |institute|     school = institute.pluck(:name)     page = Wikipedia.find(school)     description = page.summary     picture = page.image_urls.first     Institute.update!(description: description, picture: picture)  end  

I'm clearly doing something wrong here to do with the selection and use of the name attribute to find the Wikipedia page, but can't quite work it out. I think even if I were to pluck the name correctly, it wouldn't assign anything to the right id.

If there's also a way to drop the "The" at the beginning of the name in the Wikipedia search if it exists in :name, that would also be helpful as it seems some institutes drop this on Wikipedia.

Setup react-routing with rails app

Posted: 21 Jan 2017 05:26 AM PST

I am newbie for React, I know rails, I have created basic React application that perform CRUD operation.

Now, I tried to implement routing with react and want to redirect a page after successful login.

I have used gem 'react-rails' and gem 'react-router-rails' in my app.

Please instruct me with basic step to setup react route.

Thanks in advance.

using prepend_view_path to manage multiple domains on same app

Posted: 21 Jan 2017 05:02 AM PST

I'm trying to run several domains on my rails app where a lot of the view codes is shared. In order to do this I've created the following directory structure

- views      - shared      - domain1      - domain2  

I'ved added a before_filter in my application controller like so

before_filter :add_domain_view_paths    def add_domain_view_paths    prepend_view_path "app/views/shared"    prepend_view_path "app/views/#{app_domain}"  end  

After making this change and moving all current views into the app/views/shared my app suddenly started to slow down and also leak memory. No other changes were made at the time

This graph shows response times before and after making the change enter image description here Performance also seems to degrade when leaving the views in their original app/views/controller_name folder and only including the include filter as I've described above. Though there still seems to be a memory leak originating from this before_filter.

What am I doing wrong?

Rails; Fetch records within initializer

Posted: 21 Jan 2017 05:23 AM PST

I've been wondering it is common to fetch records within initializer?

Here this is an example for service object to fetch records and generated pdf receipt file.

Input is invoice uuid, and fetch the related records such as card detail, invoice items within initialier.

    class Pdf::GenerateReceipt        include Service          attr_reader :invoice, :items, :card_detail          def initialize(invoice_uuid)          @invoice ||= find_invoice!(invoice_uuid) # caching          @items = invoice.invoice_items          @card_detail = card_detail        end        .....          def call          return ReceiptGenerator.new(            id: invoice.uuid, # required            outline: outline, # required            line_items: line_items, # required            customer_info: customer_info          )         rescue => e          false, e        end         .....          def card_detail          card_metadata = Account.find(user_detail[:id]).credit_cards.primary.last            card_detail = {}          card_detail[:number] = card_metadata.blurred_number          card_detail[:brand] = card_metadata.brand          card_detail        end     end    Pdf::GenerateReceipt.('28ed7bb1-4a3f-4180-89a3-51cb3e621491') # => then generate pdf  

The problem is if the records not found, this generate an error. I could rescue within the initializer, however that seems not common.

How could I work around this in more ruby way?

missing requiered keys: [:post_id], add comments to post on a page with many posts

Posted: 21 Jan 2017 07:15 AM PST

I'm trying to add comments to my posts. When I have done that successfully before I cannot get it right now. The problem is that I have lots of posts on the same page, all of them with a comment box underneath (much like any social network).

However the page will not even render displaying this error:

No route matches {:action=>"new", :controller=>"comments", :post_id=>nil} missing required keys: [:post_id]  

Although its sending the right project id, it cannot find the post_id as there are many posts on the page (I think thats the problem... right?).

Please see below my associations:

routes.rb

  resources :projects do      resources :comments, :posts    end      resources :posts do       resources :comments    end  

Models

class Project < ApplicationRecord    belongs_to :user    has_many :comments, dependent: :destroy    has_many :posts, dependent: :destroy    class Post < ApplicationRecord    belongs_to :user    belongs_to :project    has_many :comment, dependent: :destroy    class Comment < ApplicationRecord    belongs_to :user    belongs_to :project    belongs_to :post  

Form

<%= form_for(@post, new_post_comment_path(@post)) do |f| %>  

comments controller

class CommentsController < ApplicationController    before_action :find_post    def create      @project = Project.find(params[:project_id])    @post = Post.find(params[:post_id])    @comment = current_user.comments.build(comment_params)    @comment.user_id = current_user.id         if @comment.save        flash[:success] = "Comment created!"        redirect_to @project      else        @projectboard_items = []        flash[:danger] = "Sorry! your comment was not created"        redirect_to :back      end    end       private      def find_post      @post = Post.find(params[:post_id])    end  

Thanks in advance!

Rails 5 - vendor assets are not loaded on production (fonts only)

Posted: 21 Jan 2017 06:31 AM PST

It's perfectly working in development, but not in production. It's not finding the following files:

/assets/fontello.woff
/assets/fontello.ttf

Here is the setup:

  1. fonts files:

enter image description here

  1. assets.rb

    Rails.application.config.assets.paths << Rails.root.join('app', 'vendor', 'assets', 'fonts')  Rails.application.config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/  
  2. fontello.css

    @font-face {    font-family: 'fontello';      src: url('/assets/fontello.eot');      src: url('/assets/fontello.eot#iefix') format('embedded-opentype'),      url('/assets/fontello.woff') format('woff'),      url('/assets/fontello.ttf') format('truetype'),      url('/assets/fontello.svg#fontello') format('svg');    font-weight: normal;    font-style: normal;  }  

As I said, everything is working fine in development. I have try a lot of things. For example:

  1. moving the fonts in the public folder (as my images there are loaded)
  2. add the following line in the assets.rb:

    Rails.application.config.assets.precompile += [/^[-_a-zA-Z0-9]*\..*/]  

but nothing worked.

Could you advise anything else to try?

Bundler trying to install development gems in production

Posted: 21 Jan 2017 04:03 AM PST

When I try to deploy my Rails 5 application using Capistrano 3, it tries to install development gems even in staging. This is completely new behaviour and I have no idea where it's coming from (came in the middle of a bunch of commits to a controller, the deploy scripts or Gemfile weren't touched at all).

The relevant lines of the capistrano.log are:

bash: line 1: 13108 Killed /path/to/my/app/rvm1scripts/rvm-auto.sh 2.4.0 bundle install --path /path/to/my/app/shared/bundle --without development test --deployment --quiet  bundle stderr: Nothing written  ** DEPLOY FAILED  ** Refer to log/capistrano.log for details.  

My capistrano.log can be found at this gist, but the gist of it is that it checks the bundle, which fails because the group :development gems aren't installed (obviously), and then tries to bundle install, which won't happen because they're in the development group. It's a weird, cyclical problem.

Heroku code=H10 app crashed

Posted: 21 Jan 2017 05:29 AM PST

I am new to Heroku and rails. I've read articles to create APIs for my phone app.

I have succeeded in creating locally and when I run server, the APIs respond correctly, but when I try to use the heroku link to my app I get error in log\console saying

at=error code=H10 desc="App crashed" method=GET path="/api/v1/carbrands/" host=b-taxi-server.herokuapp.com request_id=283223f5-f68d-4c4a-bb70-3346a2e3327f fwd="156.205.91.128" dyno= connect= service= status=503 bytes=    at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=b-taxi-server.herokuapp.com request_id=10510255-6149-4583-8886-6bbb69f37aaa fwd="156.205.91.128" dyno= connect= service= status=503 bytes=    /app/app/controllers/Api/V1/carbrands_controller.rb:1:in `<top (required)>': uninitialized constant Api (NameError)          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:472:in `block (2 levels) in eager_load!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:471:in `each'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:471:in `block in eager_load!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:469:in `each'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:469:in `eager_load!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:346:in `eager_load!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/application/finisher.rb:56:in `each'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/application/finisher.rb:56:in `block in <module:Finisher>'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `instance_exec'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `run'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/initializable.rb:55:in `block in run_initializers'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:226:in `block in tsort_each'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:429:in `each_strongly_connected_component_from'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:347:in `block in each_strongly_connected_component'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `each'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `call'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/initializable.rb:54:in `run_initializers'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/application.rb:352:in `initialize!'          from /app/config/environment.rb:5:in `<top (required)>'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/application.rb:328:in `require_environment!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:142:in `require_application_and_environment!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:67:in `console'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'          from bin/rails:4:in `require'          from bin/rails:4:in `<main>'  

Carbrands controller is under $$\app\controllers\Api\V1\carbrands_controller.rb

I've controller carbrands_controller.rb which has following

class Api::V1::CarbrandsController < ApplicationController    respond_to :json    skip_before_filter :verify_authenticity_token      def index          output_brands       end        def output_brands        brands = CarBrand.all        #@trips = Trip.all        if brands          respond_to do |format|          format.html          format.json { render :json => brands.to_json, status: status } #see if you want to send the cars for each user or not          end        else          output_error(401, @noBrands_found)        end            end    end  

in my routes I have

Rails.application.routes.draw do    #api routes path    #devise_for :users    namespace :api, defaults: { format: :json } do      namespace :v1 do        resources :carbrands,  only: [:create, :index]      end    end  end  

I am not sure what is wrong to be honest. I've pushed the code using git push heroku master

How do I fix that error?

How do I go about adding business_day, opening_time, and closing_time to my app?

Posted: 21 Jan 2017 03:59 AM PST

What I want to accomplish in my form is like that of the Hours field in the yelp's business form where a user can set an opening and closing time for a specific day.

Do I have to add a column through migration let's say business_time, opening_time, closing_time or there's a gem for this? Can someone point me to the right direction?

Scraping HTML table with Nokogiri and saving to database

Posted: 21 Jan 2017 03:49 AM PST

I've been trying to scrape a website for education information to save to my app database. The site has a three column table as follows:

<thead>  <tr height="20">  <th height="20" scope="col" width="91">UKPRN</th>  <th scope="col" width="87">INSTID</th>  <th scope="col" width="264">Name</th>  </tr>  </thead>  <tbody>  <tr height="20">  <td height="20">10000291</td>  <td>0047</td>  <td>Anglia Ruskin University</td>  </tr>  <tr height="20">  <td height="20">10007759</td>  <td>0108</td>  <td>Aston University</td>  </tr>  <tr height="20">  <td height="20">10000571</td>  <td>0048</td>  <td>Bath Spa University</td>  </tr>  <tr height="20">  <td height="20">10007850</td>  <td>0109</td>  <td>The University of Bath</td>  </tr>  <tr height="20">  <td height="20">10007152</td>  <td>0026</td>  <td>University of Bedfordshire</td>  </tr>  <tr height="20">  <td height="20">10007760</td>  <td>0127</td>  <td>Birkbeck College</td>  </tr>  <tr height="20">  <td height="20">10007140</td>  <td>0052</td>  <td>Birmingham City University</td>  </tr>  <tr height="20">  <td height="20">10006840</td>  <td>0110</td>  <td>The University of Birmingham</td>  </tr>  

and so on. I want to get the 8 figure reference, the 4 figure reference and the school name saved to my database under UKPRN, instid and name respectively.

This is the only table on the page so is easy to grab. So far my code in irb looks like this:

require 'nokogiri'  require 'open-uri'    page = Nokogiri::HTML(open(url))  rows = data.css("tr")  rows.each do |row|     name = row.css("td")[2]     ukprn = row.css("td")[0]     instid = row.css("td")[1]  end  

This seems to work ok as when I print one of the variables it seems to pick up the right data, but I can't get rid of the tags around the text, and once done, I'm not sure how I would go about saving this data to my institute model in the database. The attributes should correlate with the names given above. Any help is appreciated.

Condition on mount_uploader Carrierwave

Posted: 21 Jan 2017 02:30 AM PST

I have user model and have multiple method of signup : via form, with facebook & with gmail. User model have user_picture attribute and it mount to uploader using carrierwave. I won't to upload picture of user if their login with facebook or google but only save url picture from facebook or google. How can I use conditional on mount_uploader if user signup with facebook or google?

class User    mount_uploader :user_picture, UserPictureUploader # I try this condition but not working :if => Proc.new{|u| u.provider.blank? }   end  

Should I add another attribute for save picture from provider? I think that's bad practice, I want to use single attribute.

Rails Associations - undefined method for nil:NilClass

Posted: 21 Jan 2017 01:41 AM PST

Basic question on Rails associations with the following tables:

  • Shop: name, network
  • Product: title, price, shop_id

Relation defined as has_many and belongs_to:

Model:

shop.rb

class Shop < ApplicationRecord      has_many   :products  end  

product.rb

class Product < ApplicationRecord       self.primary_key = "id"       belongs_to :shop  end  

Controller:

shops_controller.rb

  def show      @shop = Shop.find(params[:id])   end  

products_controller.rb

  def show      @product = Product.find(params[:id])    end  

In the Shop view I manage to reference and show all Products for each Shop without problems:

<%= @shop.name %>  <%= @shop.network %>      <% @shop.products.each do |product| %>     <%= product.title %>    <% end %>  

But the other way around in the Product view I don't manage to show the network information from the Shop table :

  <%= @product.title %>    <%= @product.shop.network %>  

This returns the following error:

undefined method `network' for nil:NilClass  

gem install mysql2 does not work

Posted: 21 Jan 2017 01:54 AM PST

I'm trying to install mysql2 gem to use in learning rails, but it just doesn't work. Reinstalling mysql or ruby doesn't work. Using ARCHFLAGS doesn't work. I can't use apt-get libmysqlclient-dev because my Mac doesn't have Ubuntu server, and anyways wouldn't this be a dependency included in mysql when installed with homebrew (as I've done)? Also I have the very latest Xcode (8.2.1). This is the complete error message (with username in place of actual user name):

Building native extensions.  This could take a while...  ERROR:  Error installing mysql2:      ERROR: Failed to build gem native extension.        current directory: /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/mysql2-0.4.5/ext/mysql2  /Users/username/.rbenv/versions/2.3.1/bin/ruby -r ./siteconf20170121-4906-1lcyftl.rb extconf.rb  checking for rb_absint_size()... yes  checking for rb_absint_singlebit_p()... yes  checking for ruby/thread.h... yes  checking for rb_thread_call_without_gvl() in ruby/thread.h... yes  checking for rb_thread_blocking_region()... no  checking for rb_wait_for_single_fd()... yes  checking for rb_hash_dup()... yes  checking for rb_intern3()... yes  checking for rb_big_cmp()... yes  -----  Using mysql_config at /usr/local/bin/mysql_config  -----  checking for mysql.h... yes  checking for SSL_MODE_DISABLED in mysql.h... yes  checking for SSL_MODE_PREFERRED in mysql.h... yes  checking for SSL_MODE_REQUIRED in mysql.h... yes  checking for SSL_MODE_VERIFY_CA in mysql.h... yes  checking for SSL_MODE_VERIFY_IDENTITY in mysql.h... yes  checking for errmsg.h... yes  checking for mysqld_error.h... yes  -----  Don't know how to set rpath on your system, if MySQL libraries are not in path mysql2 may not load  -----  -----  Setting libpath to /usr/local/Cellar/mysql/5.7.17/lib  -----  creating Makefile    To see why this extension failed to compile, please check the mkmf.log which can be found here:      /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-16/2.3.0-static/mysql2-0.4.5/mkmf.log    current directory: /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/mysql2-0.4.5/ext/mysql2  make "DESTDIR=" clean    current directory: /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/mysql2-0.4.5/ext/mysql2  make "DESTDIR="  compiling client.c  compiling infile.c  compiling mysql2_ext.c  compiling result.c  compiling statement.c  linking shared-object mysql2/mysql2.bundle  ld: library not found for -lssl  clang: error: linker command failed with exit code 1 (use -v to see invocation)  make: *** [mysql2.bundle] Error 1    make failed, exit code 2    Gem files will remain installed in /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/mysql2-0.4.5 for inspection.  Results logged to /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-16/2.3.0-static/mysql2-0.4.5/gem_make.out  

The commands I tried to install mysql2 were:

gem install mysql2  sudo gem install mysql2 (if the error was permission denied.)  sudo gem install mysql2 -v '0.4.5' -- --with-mysql-config=/usr/local/Cellar/mysql/5.7.17/bin/mysql_config  ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future sudo gem install mysql2 -v '0.4.5'  

Not sure what exactly those mean, as I did them following advice from similar posts.

Please help. Thanks!

Dynamically include associations for objects in Rails

Posted: 21 Jan 2017 01:28 AM PST

I am currently developing a small Rails 5 application where I need to pass on an ActiveRecord object to an external service based on certain events. In my model I have defined the following:

# /models/user.rb  after_create :notify_external_service_of_user_creation    def notify_external_service_of_user_creation    EventHandler.new(      event_kind: :create_user,      content: self    )  end  

The EventHandler is then converting this object to JSON and is sending it through an HTTP request to the external service. By calling .to_json on the object this renders a JSON output which would look something like this:

{    "id":1234,    "email":"test@testemail.dk",    "first_name":"Thomas",    "last_name":"Anderson",    "association_id":12,    "another_association_id":356  }  

Now, I need a way to include all first level associations directly into this, instead of just showing the foreign_key. So the construct I am looking for would be something like this:

{    "id":1234,    "email":"test@testemail.dk",    "first_name":"Thomas",    "last_name":"Anderson",    "association_id":{      "attr1":"some_data",      "attr2":"another_value"    },    "another_association_id":{      "attr1":"some_data",      "attr2":"another_value"    },  }  

My first idea was to reflect upon the Model like so: object.class.name.constantize.reflect_on_all_associations.map(&:name), where object is an instance of a user in this case, and use this list to loop over the associations and include them in the output. This seems rather tedious though, so I was wondering if there would be a better way of achieving this using Ruby 2.4 and Rails 5.

how to test json using swagger

Posted: 20 Jan 2017 11:19 PM PST

I have created a json which returns a account info. I am trying to test it on swagger. This is what i did so far:

  1. downloaded zip folder from the location below

https://github.com/swagger-api/swagger-ui

  1. copied dist folder from zip and put in public folder of my project.

But when i do localhost:3001/dist/index.html, it wont show the action i have in controller.

can someone direct me what i am doing wrong or direct me to any online article?

Thanks

Passenger error: Could not spawn process for application /home/user/app/current

Posted: 20 Jan 2017 10:48 PM PST

I'm setting up a Rails app using Nginx and Passenger on Digital Ocean, but I'm getting an error when visiting the IP address.

We're sorry, but something went wrong.

I can confirm the directory being referenced because I can navigate there and run pwd. => ~/app/current/public/assets

Error Log: /var/log/nginx/error.log

  Could not spawn process for application       /home/<user>/<app>/current: An error occurred while starting up the preloader.    Error ID: 1bb1fce1    Error details saved to: /tmp/passenger-error-vZPTxi.html    Message from application: Unable to autoload constant      API::Mobile::V1::BaseApiController, expected       /home/<user>/<app>/releases/20170121053748/app/controllers/api/mobile/v1/base_api_controller.rb       to define it (LoadError)  

*There is more information in a passenger-error...html file but it was very verbose so I didn't know what to include from it.

/sites-available/default:

server {          listen 80;          listen [::]:80 ipv6only=on;            server_name 127.0.0.1;          passenger_enabled on;          rails_env production;            root /home/<user>/<app>/current/public;            error_page 500 502 503 504 /50x.html;          location = /50x.html {                  root html;          }          index index.html index.htm index.nginx-debian.html;            server_name _;            location / {                  try_files $uri $uri/ =404;          }  }  

nginx.conf

user www-data;  worker_processes auto;  pid /run/nginx.pid;    events {          worker_connections 768;  }  http {          sendfile on;          tcp_nopush on;          tcp_nodelay on;          keepalive_timeout 65;          types_hash_max_size 2048;            include /etc/nginx/mime.types;          default_type application/octet-stream;            ssl_protocols TLSv1 TLSv1.1 TLSv1.2;           ssl_prefer_server_ciphers on;            access_log /var/log/nginx/access.log;          error_log /var/log/nginx/error.log;            gzip on;          gzip_disable "msie6";            include /etc/nginx/passenger.conf;            include /etc/nginx/conf.d/*.conf;          include /etc/nginx/sites-enabled/*;  }  

I've seen similar questions on SO but the answers weren't able to help so far.

Is there a common solution to this?

searchkick re indexing not working on rails application production

Posted: 21 Jan 2017 01:41 AM PST

Im trying to use Searchkick in my application. However, I get

Searchkick::MissingIndexError   Index missing - run Restaurant.reindex  

I run Restaurant.reindex but it didn't solve the issue. I also tried the following: rake searchkick:reindex:all and I receive the Reindex complete message; however,I come up with the same missing index error when I submit the search query.

Do I need to deploy my rails application again on AWS?

Any advice and suggestions will be greatly appreciated.

Rails create has_many association models from a list of options

Posted: 20 Jan 2017 11:24 PM PST

I have options for timeslots that a user should be able to choose from:

[    { day_of_week: 'Thursday', time_of_day: '7 am' },    { day_of_week: 'Thursday', time_of_day: '8 am' },    { day_of_week: 'Thursday', time_of_day: '9 am' },    { day_of_week: 'Friday', time_of_day: '7 am' },    { day_of_week: 'Friday', time_of_day: '8 am' },    { day_of_week: 'Friday', time_of_day: '9 am' },    { day_of_week: 'Friday', time_of_day: '10 am' },    { day_of_week: 'Saturday', time_of_day: '8 am' },    { day_of_week: 'Saturday', time_of_day: '9 am' },    { day_of_week: 'Saturday', time_of_day: '10 am' }  ]  

User has_many :timeslots and a user should be able to select Timeslot based on the list above.

My current html:

   <%= simple_form_for(current_user, url: registration_path(:user)) do |f| %>          <% @timeslots.each do |day, values| %>            <div class="lead">              <%= day %>            </div>            <%= f.simple_fields_for :timeslots, values.sort_by { |slot| slot[:time_of_day].to_i } do |ff, something| %>              <div class="form-check">                <label class="form-check-label">                  <%= ff.input_field :selected %>                  <%= ff.object.time_of_day %>                </label>              </div>            <% end %>          <% end %>          <%= f.submit 'Update', class: 'btn btn-primary' %>        <% end %>  

I'd like to do two things: 1. Not have to prebuild timeslots in the database for a user 2. I can change the list (add or remove) and that would reflect the options available to the user to select from

Ruby on rails - Devise - Show user created content only

Posted: 20 Jan 2017 08:52 PM PST

I am creating a basic ruby on rails application similar to zapier or ifttt. Users create recipes. I'd like to ONLY display recipes created by the user.

I've used device gem for authentication.

My questions:

Do i add "if user_signed_in?" on the top of each page? Can I add above yield on application layouts? Is there a better way?

Do i nest recipes within users?

crossing borders of tables: language role

Posted: 20 Jan 2017 08:24 PM PST

I'm new to development, and have spent the last 12 hours (literally) trying to figure out this error message - I'm giving up for the night, but not before a quick cry for help to stackoverflow.

I have this form:

<h2>Select from the language options below (or, <%= button_to "Login", 'users/login', method: :get %></h2>    <%= form_for @language_role do |f| %>        <div id="input">        <h3>I want to learn:</h3><%= select_tag(:language_id, options_from_collection_for_select(Language.all, :id, :lang_name)) %>      </div>        <div>        <p><%= f.submit "Start learning" %></p>      </div>  <% end %>  

which is giving me this error message, highlighting the line @language_role = current_user.language_roles.build : "undefined method `language_roles' for nil:NilClass"

I have three tables:

  create_table "language_roles", force: :cascade do |t|      t.integer  "language_id"      t.boolean  "is_active"      t.boolean  "is_teacher"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.integer  "user_id"      t.index ["user_id"], name: "index_language_roles_on_user_id"    end      create_table "languages", force: :cascade do |t|      t.string   "lang_name"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "users", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.index ["email"], name: "index_users_on_email", unique: true      t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true    end  

The language_roles table is meant to allow a user to have many languages, as well as many roles within that language. Here are my class definitions:

class LanguageRole < ApplicationRecord    belongs_to :languages    belongs_to :users  end    class Language < ApplicationRecord    has_many :language_roles    has_many :users, :through => :language_roles  end    class User < ApplicationRecord    has_many :language_roles    has_many :languages, :through => :language_roles    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable  end  

My root path goes to 'home#index', where the user is supposed to pick a language if current_user.language_roles is empty. As such, I put this code in my home controller and language_roles controller:

class HomeController < ApplicationController        def index          @language_role = current_user.language_roles.build        end      end    class LanguageRolesController < ApplicationController      def create      @language_role = current_user.language_roles.build(language_role_params)      if @language_role.save        redirect_to root_path      else        redirect_to :back      end    end      private      def language_role_params      params.permit(:language_id)    end  end  

What in the hell is the problem?? I assume I need to instantiate the variable somehow, but I'm not sure how.

Thanks, Michael

Build method is not associating in Rails

Posted: 20 Jan 2017 06:56 PM PST

I'm still newbie in Rails, but got confused with the initialization of a HABTM association. Reading its documentation, it says

When initializing a new has_one or belongs_to association you must use the build_ prefix to build the association, rather than the association.build method that would be used for has_many or has_and_belongs_to_many associations.

So, basically, let's suppose we have two models:

class User < ApplicationRecord    has_and_belongs_to_many :organizations  end    class Organization < ApplicationRecord    has_and_belongs_to_many :users  end  

Inside organization_controller, since I'm using Devise, my create method should have something like this:

@organization = current_user.organizations.build(organization_params)  @organization.save  

However, it is not working. With byebug, I checked that for the current_user.organizations, the new organization was there, but, if I call @organization.users, there's an empty array. Looks like it's required to run current_user.save as well, is it correct? I was able to associate both models with this code:

@organization = Organization.new(organization_params)  @organization.users << current_user  @organization.save  

Tinymce default styles in Rails app

Posted: 20 Jan 2017 04:49 PM PST

I was following the tutorial on How to build a blog with Rails 5 and Bootstrap 4 - Part 5, initialized Tinymce Editor but I can't change the default font size of text in this editor. I have this code in application.js:

document.addEventListener("turbolinks:load", function() {    tinymce.remove();    tinymce.init({        selector: 'textarea#post_body',    height: 500,    plugins: [        "advlist autolink autosave link image lists charmap",        "wordcount media code",        "table contextmenu textcolor paste"      ],    toolbar1: "undo redo | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect",    toolbar2: "cut copy paste | bullist numlist | outdent indent blockquote | link image media | forecolor | table | subscript superscript | charmap | code",    menubar: false,    content_css : "/assets/application.css"  });  

})

In application.css:

 *= require_tree .   *= require_self  @import "bootstrap-sprockets";  @import "bootstrap";  @import "font-awesome";  

And there are other two files with styles (custom.scss and posts.scss). I tried putting in custom.scss:

body.mce-content-body {      font-size: 16px;      background-color: gray;}    body.mce-content-body p {      font-size: 16px;}    [data-mce-style] {      font-size: 16px;}  

I also tried the following:

-clearing browser cache several times

-copying custom.scss and linking to the new file in content_css as per this suggestion

-using content_style: ".mce-content-body p { font-size: 16px;}"

The file is being added to the head of the iframe and its background color is changing, but the styles for paragraphs are always being overwritten by their default inline styles :<p style="box-sizing: border-box; margin: 0px 0px 1.1em; padding: 0px; border: 0px; font-size: 19.35px; line-height: 32.895px; font-family: Lato, sans-serif; color: #444444;" data-mce-style="box-sizing: border-box; margin: 0px 0px 1.1em; padding: 0px; border: 0px; font-size: 19.35px; line-height: 32.895px; font-family: Lato, sans-serif; color: #444444;">...</p>

Another problem is that even if I change the background-color while editing post, the default styles are back when I submit the form and show all blog posts :(

Any ideas, please?

ODD ISSUE: Heroku app works great on few computers but not the others. Could running "heroku restart" cause the issue?

Posted: 20 Jan 2017 05:59 PM PST

I am running into a very odd issue and coming up short with identifying the issue. I don't even know if it is a front-end, server or heroku issue. Please help me out.

I am managing a Rails App (with React front-end), hosting on Heroku. It is a workforce management and dispatching app. It has been working fine the whole time, until earlier today, when I made a huge feature deployment. The deployment was successful, and I tested the old & new features fine on all of our testing computers. After deployment, I ran heroku run rake db:migrate and heroku restart. During this time, we have customers using the web app on their local computers, in different time zones.

Few minutes later, I got a call from multiple customers, each mentioning that at least one of their dispatching features is not working, all of which were older features/components that shouldnt have been affected. Some say they cant see their workers. One say they cant see jobs on a particular day. Some say they cant see jobs on another. When I check the heroku logs, I see no errors whatsoever. Routes are called fine and things are passed correctly back to the front-end. When logging into their app with master credentials, we also were unable to replicate ANY of these issues on ANY of our computers. All of our customers uses Chrome, but checking on both Mac and Windows reveal no issues from our ends. Yet, the issue still remains.

We then decided to revert our deployment and deployed an earlier version. Same thing. Everything works on ours, and customers continue to say these features/components just appear...blank. We tried heroku run rake tmp:clear to clear heroku cache, still no luck.

Thank you. Any comments will be highly appreciated.

Strong Params: params.permit returns Unpermitted parameters despite whitelist

Posted: 20 Jan 2017 06:54 PM PST

UsersProfileController has strong params that looks like so:

    def user_profile_params        params.permit(:age, :relations)        # yes, I am not requiring user_profile. Just permitting attributes I need.       end  

The create action builds UserProfile through a parent (has-one and belongs-to association)

    def create        parent = Parent.create_guest        parent.build_user_profile(user_profile_params)        if parent.save           # do something         else           # handle error        end      end  

Calling params in UserProfiles returns:

    <ActionController::Parameters         {"age"=>"23",          "relations"=>"3",          "subdomain"=>"api",          "format"=>:json,          "controller"=>"api/v1/user_profiles",          "action"=>"create"}        permitted: false>  

Calling user_profile_params, returns this:

    user_profile_params:        Unpermitted parameters: subdomain, format        <ActionController::Parameters          {"age"=>"23",          "relations"=>"3", }         permitted: true>  

When a post request comes in, I expect to be able to create user_profile using the whitelisted params in user_profile_params. Instead, the create action in UserProfiles fails with error: Unpermitted parameters: subdomain, format.

This isn't what I expected. I expected user_profile_params to only include the permitted values and ignore all others.

I could add :format and :subdomain to list of permitted attributes but something feels a bit off about that.

Can someone explain what is going on/what I am missing?

No comments:

Post a Comment