Rails database is correct, but schema.rb is not Posted: 05 Jun 2016 06:57 AM PDT I recently switched from using sqlite to postgres on an existing rails app. I am not able to update the schema.rb file past the last migration migrated under SQLite. When I complete a rake db:reset, I get this message (suggesting I have created a clubs table and a memberships table, amongst other things): $ rake db:reset-- enable_extension("plpgsql") -> 0.0238s -- create_table("accomplishments", {:force=>:cascade}) -> 0.0258s -- create_table("clubs", {:force=>:cascade}) -> 0.0233s -- add_index("clubs", ["goal_id"], {:name=>"index_clubs_on_goal_id", :using=>:btree}) -> 0.0200s -- create_table("friendships", {:force=>:cascade}) -> 0.0172s -- create_table("goals", {:force=>:cascade}) -> 0.0219s -- create_table("impressions", {:force=>:cascade}) -> 0.0279s -- create_table("memberships", {:force=>:cascade}) -> 0.0200s -- add_index("memberships", ["club_id"], {:name=>"index_memberships_on_club_id", :using=>:btree}) -> 0.0200s -- add_index("memberships", ["user_id"], {:name=>"index_memberships_on_user_id", :using=>:btree}) -> 0.0127s -- create_table("users", {:force=>:cascade}) -> 0.0253s -- add_index("users", ["email"], {:name=>"index_users_on_email", :unique=>true, :using=>:btree}) -> 0.0156s -- add_index("users", ["reset_password_token"], {:name=>"index_users_on_reset_password_token", :unique=>true, :using=>:btree}) -> 0.0092s -- add_foreign_key("clubs", "goals") -> 0.0060s -- add_foreign_key("memberships", "clubs") -> 0.0054s -- add_foreign_key("memberships", "users") -> 0.0063s -- initialize_schema_migrations_table() -> 0.0359s -- enable_extension("plpgsql") -> 0.0220s -- create_table("accomplishments", {:force=>:cascade}) -> 0.0216s -- create_table("clubs", {:force=>:cascade}) -> 0.0153s -- add_index("clubs", ["goal_id"], {:name=>"index_clubs_on_goal_id", :using=>:btree}) -> 0.0086s -- create_table("friendships", {:force=>:cascade}) -> 0.0108s -- create_table("goals", {:force=>:cascade}) -> 0.0167s -- create_table("impressions", {:force=>:cascade}) -> 0.0125s -- create_table("memberships", {:force=>:cascade}) -> 0.0119s -- add_index("memberships", ["club_id"], {:name=>"index_memberships_on_club_id", :using=>:btree}) -> 0.0115s -- add_index("memberships", ["user_id"], {:name=>"index_memberships_on_user_id", :using=>:btree}) -> 0.0082s -- create_table("users", {:force=>:cascade}) -> 0.0154s -- add_index("users", ["email"], {:name=>"index_users_on_email", :unique=>true, :using=>:btree}) -> 0.0111s -- add_index("users", ["reset_password_token"], {:name=>"index_users_on_reset_password_token", :unique=>true, :using=>:btree}) -> 0.0175s -- add_foreign_key("clubs", "goals") -> 0.0050s -- add_foreign_key("memberships", "clubs") -> 0.0048s -- add_foreign_key("memberships", "users") -> 0.0041s -- initialize_schema_migrations_table() -> 0.0173s But my schema.rb file shows an out-of-date timestamp and does not include newer changes: ActiveRecord::Schema.define(version: 20160516084731) do create_table "accomplishments", force: :cascade do |t| t.integer "goal_id" t.string "title" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "friends", force: :cascade do |t| t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "goals", force: :cascade do |t| t.integer "user_id" t.string "title" t.text "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "users", force: :cascade do |t| t.datetime "created_at", null: false t.datetime "updated_at", null: false 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.string "first_name" t.string "last_name" end add_index "users", ["email"], name: "index_users_on_email", unique: true add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end I am using the pg gem and have removed the sqlite gem. Database.yml: development: adapter: postgresql encoding: unicode database: PA_development template: template0 pool: 5 username: postgres password: password test: adapter: postgresql encoding: unicode database: PA_test template: template0 pool: 5 username: postgres password: password How do I update the schema? |
Ruby on Rails - Postgres error when trying to start Rails Server Posted: 05 Jun 2016 06:56 AM PDT I am using: - ruby 2.2.1
- rails 4.6.2
- homebrew for postgres installation
- rbenv
- osx el capitan 10.11.5
Here is the error I receive when running: rails s /usr/local/lib/ruby/gems/2.2.0/gems/pg-0.18.4/lib/pg.rb:4:in `require': dlopen(/usr/local/lib/ruby/gems/2.2.0/gems/pg-0.18.4/lib/pg_ext.bundle, 9): Library not loaded: /usr/local/lib/libruby.2.2.0.dylib (LoadError) Referenced from: /usr/local/lib/ruby/gems/2.2.0/gems/pg-0.18.4/lib/pg_ext.bundle Reason: image not found - /usr/local/lib/ruby/gems/2.2.0/gems/pg-0.18.4/lib/pg_ext.bundle from /usr/local/lib/ruby/gems/2.2.0/gems/pg-0.18.4/lib/pg.rb:4:in `<top (required)>' from /usr/local/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:86:in `require' from /usr/local/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:86:in `block (2 levels) in require' from /usr/local/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:81:in `each' from /usr/local/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:81:in `block in require' from /usr/local/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:70:in `each' from /usr/local/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:70:in `require' from /usr/local/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler.rb:102:in `require' from /Users/jeffr/Dropbox/DevelopmentPC/rails4/myapp/config/application.rb:7:in `<top (required)>' from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:78:in `require' from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:78:in `block in server' from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `tap' from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `server' from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!' from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>' from /Users/jeffr/Dropbox/DevelopmentPC/rails4/myapp/bin/rails:9:in `require' from /Users/jeffr/Dropbox/DevelopmentPC/rails4/myapp/bin/rails:9:in `<top (required)>' from /usr/local/lib/ruby/gems/2.2.0/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in `load' from /usr/local/lib/ruby/gems/2.2.0/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in `call' from /usr/local/lib/ruby/gems/2.2.0/gems/spring-1.7.1/lib/spring/client/command.rb:7:in `call' from /usr/local/lib/ruby/gems/2.2.0/gems/spring-1.7.1/lib/spring/client.rb:30:in `run' from /usr/local/lib/ruby/gems/2.2.0/gems/spring-1.7.1/bin/spring:49:in `<top (required)>' from /usr/local/lib/ruby/gems/2.2.0/gems/spring-1.7.1/lib/spring/binstub.rb:11:in `load' from /usr/local/lib/ruby/gems/2.2.0/gems/spring-1.7.1/lib/spring/binstub.rb:11:in `<top (required)>' from /usr/local/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from /usr/local/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from /Users/jeffr/Dropbox/DevelopmentPC/rails4/myapp/bin/spring:13:in `<top (required)>' from bin/rails:3:in `load' from bin/rails:3:in `<main>' |
devise ajax sign in handling failure on rails 4 Posted: 05 Jun 2016 06:44 AM PDT I am trying to receive login fail events on a devise AJAX login form. I have overriden the devise sessions controller like so: class SessionsController < Devise::SessionsController def create resource = warden.authenticate!(:scope => resource_name, :recall => '#{controller_path}#failure') sign_in_and_redirect(resource_name, resource) end def sign_in_and_redirect(resource_or_scope, resource=nil) scope = Devise::Mapping.find_scope!(resource_or_scope) resource ||= resource_or_scope sign_in(scope, resource) unless warden.user(scope) == resource return render :json => {:success => true} end def failure return render :json => {:success => false, :errors => ["Login failed."]} end end the json on failure never actually triggers on a 401 unauthorised response. The js on sign_in_and_redirect works fine though. Here is the section of my js where i expect an alert to show: $(document).on('click', '#login-btn', function(){ $("#login-modal").toggleClass("is-active"); $("form#login_user_form").bind("ajax:success", function(e, data, status, xhr) { if (data.success) { $("#login-modal").toggleClass("is-active"); } else { return alert('failure!'); // this never happens } }); }); |
Multiple image upload Rails Posted: 05 Jun 2016 05:55 AM PDT I have been stuck on a problem for three weeks now, and although I have tried everyday to find an answer to my problem, I haven't found anything that I have been able to make work. If anyone could help me, I would be very, very grateful. I have built a basic blog in Rails that allows an admin user to publish articles using a form, containing a title text_field, body text_area, and file_field for an image, which uses Paperclip. All very simple and easy and no problems there. However, I have been trying to alter the form to allow an admin user to upload multiple images as part of a new article, but have been unable to find a way to do this. I need a solution that will allow me to achieve multiple image upload functionality in a form. I have tried many gems and many tutorials, but have been unable to integrate anything into my app without completely breaking it. Can any one help me get out of this dead end I've found myself in for the last three weeks? Do you have any clear tutorials or solutions that will help me overcome this problem? Thank you very much to anyone that can help me. |
current_page? inside controller Posted: 05 Jun 2016 06:42 AM PDT Is there any easy way of using something like current_page? method from ActionView::Helpers::UrlHelper inside controller? I have routing like: resources :addresses resources :mailing_addresses, :controller => 'addresses' And I would like to do a check in my controller that would look like this: class AddressesController def index if current_page?(live_addresses_path) # ... logic goes here elsif current_page?(addresses_path) # ... logic goes here end end end What's the easiest way of achieving it? |
Using dotenv for production - cannot deploy with Capistrano 3 because of not loading constants Posted: 05 Jun 2016 05:42 AM PDT I have saved some data in .env.production , I am loading dotenv in application.rb : require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(:default, Rails.env) Dotenv::Railtie.load In config/environments/production.rb , I am using a constant from .env.production like ENV['REDIS_IP'] , but when deploying with Capistrano 3, I get this error: SSHKit::Command::Failed: rake exit status: 1 rake aborted! ArgumentError: invalid uri scheme '' Which says that were should be the ENV['REDIS_IP'] , there's nothing. .env.production is not in .gitignore . Why the application cannot fetch the data from dotenv file? Thank you in advance. |
Unable to install ImageMagick-7.0.1-Q16 to work with rails Posted: 05 Jun 2016 06:53 AM PDT I've installed the latest version of the Rails Installer (ruby 2.2 and rails 4.2). I'm trying to install paperclip and as part of the process need to install imagemagick. Imagemagick is giving me trouble. I've installed the latest version of imagemagick (7.0.1-Q16). I'm on a 64bit Windows 10 machine. What I have tried is the following: - I installed the .dll file and then afterward i installed the static file (note when i did this some of the files in the static installation asked me if i wanted to overwrite some of the .dll files).
- I used the 32 bit version which ends up in Program Files(x86). I named the folder ImageMagick & that didn't work. So I left it as the installed ImageMagick-7.0.1-Q16 folder.
The error message I got from trying to use the convert command inside imagemagick folder is: C:\Program Files (x86)\ImageMagick-7.0.1-Q16>convert: unable to open image 'logo.gif': Permission denied @ error/blob.c/OpenBlob/2695. The error message I get with trying to install it in my rails app is: gem install rmagick --platform=ruby -- '--with-opt-dir="C:Program Files(x86)ImageMagick-7.0.1-Q16"' Temporarily enhancing PATH to include DevKit... Building native extensions with: '--with-opt-dir="C:Program Files(x86)ImageMagick-7.0.1-Q16"' This could take a while... ERROR: Error installing rmagick: ERROR: Failed to build gem native extension. C:/RailsInstaller/Ruby2.2.0/bin/ruby.exe -r ./siteconf20160605-8596-1h37a34.rb extconf.rb --with-opt-dir="C:Program Files(x86)ImageMagick-7.0.1-Q16" checking for main() in -lCORE_RL_magick_... no searching PATH for the ImageMagick library... Can't install RMagick 2.15.4. Can't find the ImageMagick library. Retry with '--with-opt-dir' option. Usage: gem install rmagick -- '--with-opt-dir="[path to ImageMagick]"' e.g. gem install rmagick -- '--with-opt-dir="C:Program FilesImageMagick-6.9.1-Q16"' *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Any ideas would be great. Thanks. |
Rails associations - NoMethodError: undefined method Posted: 05 Jun 2016 05:13 AM PDT Working on project with associations between Invoices and Vat (both models). Every time I try to get a value of the Vat through the console like @Invoice.last.vat.amount I get the message Rails associations - NoMethodError: undefined method I think I have the migrations done correctly but somehow I'm overlooking something: My models: class Vat < ActiveRecord::Base belongs_to :invoice end class Invoice < ActiveRecord::Base has_many :vats belongs_to :client end My migrations: For Invoices class CreateInvoices < ActiveRecord::Migration def change create_table :invoices do |t| t.datetime :issue_time t.integer :total t.integer :vat t.string :item t.string :currency t.references :client, index: true t.timestamps end end end For Vat class CreateVats < ActiveRecord::Migration def change create_table :vats do |t| t.integer :amount t.string :name t.timestamps end end end And a later modification to add Vat to Invoices: class AddVatToInvoices < ActiveRecord::Migration def change add_reference :invoices, :vat, index: true end end |
Rails JSON API: limit has_many relationship to current_user Posted: 05 Jun 2016 06:08 AM PDT I have a rails json API with 2 models (Bags and Items ). I am using active record serializers with MySQL to organize the json output. I want to show all Bags for all users, but only Items for the current user. Looking for something like this: class Bag < ActiveRecord::Base has_many :items,-> {where current_user: "#{current_user.id}"},class_name: 'Items' end I don't know of a way to pass the current_user.id property to the model. Hoping someone knows a way. |
Including part of .jsp file inside .html.erb Posted: 05 Jun 2016 06:26 AM PDT Is it possible to include a part of a .jsp file inside another .html.erb file? If yes then how? meanwhile the code I want to include is inside <c:choose> .... </c:choose> I am trying translate a .jsp file functionality in ruby on rails .html.erb file. <script>... </script> part will be identical for both. How to add other parts as mentioned, in .html.erb |
rails cancancan has_many through abilities Posted: 05 Jun 2016 04:49 AM PDT company.rb: class Company < ActiveRecord::Base has_many :companies_admins, dependent: :destroy has_many :supervisors, through: :companies_admins end companies_admin.rb: class CompaniesAdmin < ActiveRecord::Base belongs_to :company belongs_to :supervisor, foreign_key: "admin_id" end supervisor.rb: class Supervisor < Admin has_many :companies_admins, foreign_key: "admin_id" has_many :companies, through: :companies_admins, foreign_key: "admin_id" end i use cancancan gem. My ability.rb: class Ability include CanCan::Ability def initialize(user) user ||= Admin.new # guest user (not logged in) if user.type == "Administrator" can :manage, :all elsif user.type == "Supervisor" can :manage, Company, companies_admins: {supervisor: { :id => user.id } } end end end I need to supervisor only companies able to manage, with whom he has a relationship. Example: supervisor companies_admins when I open the page of company id=10 get access denied. Started GET "/companies/10" for 127.0.0.1 at 2016-06-05 14:23:01 +0300 Processing by CompaniesController#show as HTML Parameters: {"id"=>"10"} Company Load (0.4ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = $1 LIMIT 1 [["id", 10]] Admin Load (0.3ms) SELECT "admins".* FROM "admins" WHERE "admins"."id" = $1 LIMIT 1 [["id", 4]] CompaniesAdmin Load (0.4ms) SELECT "companies_admins".* FROM "companies_admins" WHERE "companies_admins"."company_id" = $1 [["company_id", 10]] Supervisor Load (0.4ms) SELECT "admins".* FROM "admins" WHERE "admins"."type" IN ('Supervisor') AND "admins"."id" = $1 LIMIT 1 [["id", 2]] Supervisor Load (0.4ms) SELECT "admins".* FROM "admins" WHERE "admins"."type" IN ('Supervisor') AND "admins"."id" = $1 LIMIT 1 [["id", 4]] Redirected to http://localhost:3000/ Completed 302 Found in 20ms (ActiveRecord: 1.9ms) The question is why? how to identify the expression "include"? |
Override Rails Admin field without hiding the other fields Posted: 05 Jun 2016 04:44 AM PDT I need to override one of my fields in Rails admin show page, I tried to override it on the model like so: class products < ActiveRecord::Base rails_admin do field :type do pretty_value do %{<a href="/admin/#{bindings[:object].type}/#{bindings[:object].id}">#{bindings[:object].type}</a>}.html_safe end end end This shows only my type fields, and hides my other ones, how to override it without hiding the other fields? Also I think this is better to be moved to an initialiser, am I correct? |
image_tag not displaying image in aws beanstalk production mode Posted: 05 Jun 2016 06:52 AM PDT I have an image tag to display my avatar. The tag works in development mode but not in the production mode when i deploy it to aws beanstalk. The place where I view the avatar picture shows up as "img 0645" Its almost as if the image gets saved but is displaying the img name in a way or id. The image itself isn't showing up!! How do i make the image show up??? Thanks!!! Im using Postgres, puma, aws beanstalk, ruby on rails Not sure if this helps but I used Find to lookup anything in the log with avatar in the search and came up with these. "GET /system/users/avatars/000/000/001/thumb/IMG_0645.JPG?1465126426 HTTP/1.1" 404 1564 "GET /system/users/avatars/000/000/001/medium/IMG_0645.JPG?1465126426 HTTP/1.1" 404 1564 |
Not creating table after running the rake db:migrate command Posted: 05 Jun 2016 03:34 AM PDT I created a migration by rails g migration brand name:string then ran it rake db:migrate This ran successfully In my schema it shows the table along with the fields But when i check that in console it says NameError: uninitialized constant Brand Is there anything else i need to run or configure? I am using ruby version 2.2.1 and rails version 4.1.4 |
handling rails timezone in several users namespaces, also how does around_action works? Posted: 05 Jun 2016 02:47 AM PDT I have a rails app with several namaspaces such as user, management, admin. which means I have current_user, current_management, current_admin. How should I handle timezone settings for these different user namespaces. I read this (https://robots.thoughtbot.com/its-about-time-zones) but it shows current_user. What should I do with current_management ? what does "around_action" actually do in this context ? if the user updates the timezone, what happens, or is there something i should set explicitly ? when I display the time, should i always do in_time_zone ? if I need to do that why have the application controller code ? https://robots.thoughtbot.com/its-about-time-zones here is a code it request to put in application controller # app/controllers/application_controller.rb around_action :set_time_zone, if: :current_user private def set_time_zone(&block) Time.use_zone(current_user.time_zone, &block) end it says to display in current time zone like this <%= time.in_time_zone(current_user.time_zone) %> |
How to use response from nokogiri web scrape Posted: 05 Jun 2016 02:36 AM PDT So i have this web scrape returning like this... pastebin.com/CMrFcBMX This has everything i need to make my website work. However when i pass it through as json it returns like this: [ [ "formatted_total_price", "£66.00" ], [ "formatted_total_price", "£128.00" ], [ "formatted_total_price", "£246.00" ], [ "formatted_total_price", "£243.20" ], [ "formatted_total_price", "£242.86" ], [ "formatted_total_price", "£242.50" ], [ "ticket_desc", "Later Owl Ticket" ], [ "ticket_desc", "Later Owl Ticket+Collector Ticket @ extra £4.95 per ticket" ], [ "ticket_desc", "Later Owl + Chance For VIP Upgrade" ], [ "ticket_desc", "VIP Ticket" ], [ "ticket_desc", "VIP Ticket + Collector Ticket @ extra £4.95 per ticket" ], [ "ticket_desc", "Skydeck Package" ], [ "ticket_desc", "5 Person Skydeck Table" ], [ "ticket_desc", "7 Person Skydeck Table" ], [ "ticket_desc", "10 Person Skydeck Table" ] ] As you can see each array links together. Furthermore If you ignore all the ticket_desc that have a + in it, They match, E.g, [ "formatted_total_price", "£66.00" ], Matches [ "ticket_desc", "Later Owl Ticket" ], How would i go about making this look better and make it more usable in my ajax call? Heres my ruby file right now which does the actual webscrape. def ticketmaster ticketmaster_url = "http://www.ticketmaster.co.uk/event/"+ params[:tmid] doc = Nokogiri::HTML(open(ticketmaster_url)) event_name = nil ticket_price = nil doc.xpath("//script[@type='text/javascript']/text()").each do |text| if text.content =~ /more_options_on_polling/ price1 = text.to_s.scan(/\"(formatted_(?:total_price))\":\"(.+?)\"/).uniq description = text.to_s.scan(/\"(ticket_desc)\":\"(.+?)\"/).uniq price = price1 + description render json: price end end end I have looked into jbuilder, however this started to confuse me very very fast!!! The end goal is to have the ticket_desc in one column of a table and the price in another column. The ajax code is pratically all set up for this. Its just getting it to work correctly. Ajax code: $.ajax({ type: 'GET', crossDomain: true, dataType: 'json', success: function(json) { for (var i = 0; i < json.length; i++) { var section = json[i][0]; var price = json[i][1]; debugger; If you need anymore code, let me know. The code above has some things removed such as the url. but thats the basic premise. I'm just struggling to parse the data returned. |
Heroku not starting workers Posted: 05 Jun 2016 05:44 AM PDT My Heroku app is not starting any workers. I scale the worker first: heroku ps:scale resque=1 -a test-eagle Scaling dynos... done, now running resque at 1:Free Then when I check the workers, I see: heroku ps:workers -a test-eagle <app> is running 0 workers What could be worng here? This is how my Procfile looks: web: bundle exec puma -C config/puma.rb resque: env TERM_CHILD=1 bundle exec rake resque:work QUEUE=* COUNT=1 Or is it because it is a free app which can only handle 1 web worker and no other dynos? |
How to deauthorize User Facebook Permissions using Koala gem Posted: 05 Jun 2016 02:53 AM PDT I am using Koala to handle FB calls. Everything is working fine except I can't figure out how to deauthorize a user's FB permissions. The equivalente REST call would be to: DELETE /{user-id}/permissions/{permission-name} The Koala wiki indicates all REST calls are supported via: @rest = Koala::Facebook::API.new(oauth_access_token) @rest.fql_query(my_fql_query) # convenience method @rest.fql_multiquery(fql_query_hash) # convenience method @rest.rest_call("stream.publish", arguments_hash) # generic version but this doesn't tell me much. I would prefer to use Koala as I have app secret security enabled and generating app_secret_proof for plain FB REST calls is a major hassle. Koala handles it transparently. |
Accessing newly singed up user in Rails app using devise Posted: 05 Jun 2016 01:53 AM PDT I am currently making Rails app using devise. After a new user signs up, I need to access newly singed up user's information to run my customized function. However it seems like devise's current_user is nil since the user is not logged in yet until the user confirms the email. I essentially just need to check whether user's confirmed_at is nil. Is there a way to do this? |
Ruby Rails: Access denied for user 'root'@'localhost' (using password: YES) Posted: 05 Jun 2016 04:31 AM PDT I have read other questions similar to this one. I feel that my situation is different enough to ask again for extra possible problem. I have a Ruby on Rails app all setup. I have set up other rails projects before, so I am somewhat familiar with doing rails. My specific problem with this error: Access denied for user 'root'@'localhost' (using password: YES) Here is my database.yml file default: &default adapter: mysql2 host: localhost username: cmsapp password: <%= ENV['CMSAPP_PASSWORD'] %> <-- this line is not working port: 3306 pool: 5 timeout: 5000 development: <<: *default database: cms_dev socket: /var/run/mysqld/mysqld.sock production: <<: *default database: cms_prod The problem I am having is: it seem to me that the password is not getting parsed or pulled from the ENV['CMSAPP_PASSWORD'] environment variable. I have double/triple check the password on the mysql db. If I put the literal password on the password: line,(which I am not supposed to do) it does connect. So I do know that the password is correctly set in mysql. Ruby errors on this line: connect user, pass, host, port, database, socket, flags in the console at bottom of the page, I type in pass to see whats in the variable, and I get "<%= ENV[CMSAPP_PASSWORD] %>". if I type just 'ENV[CMSAPP_PASSWORD]' I get the correct password. So I know the right password is there, but I believe its sending the literal "<%= ENV[CMSAPP_PASSWORD] %>". So even though the correct password is in the environment variable, I still get the error: Access denied for user 'root'@'localhost' (using password: YES) How do I troubleshoot weather the password is being properly extracted from the environment variable? Or how to figure out why it is not reading the environment variable? Thanks for any help. |
How could I DRY the common methods in different model Posted: 05 Jun 2016 02:57 AM PDT I wrote setter and getter for the virtual attribute stock For the getter it will aggregate the HAM_MANY relation records. For the setter, it will create a new record and save the record to the right child table. How could I DRY the two methods in the two models? How could I avoid have two identical code in different model files? Thanks Model Flight has_many :stocks, foreign_key: "flight_sku_fare_id", class_name: "FlightSkuFareStock", dependent: :destroy def stock stocks.sum(:amount) end def stock=(stock_value) self.save stock_delta = stock_value - self.stock if stock_value >=0 and (stock_delta!=0) self.stocks.create(amount: stock_delta) end end Model Room has_many :stocks, foreign_key: "room_sku_id", class_name: "RoomSkuStock", dependent: :destroy def stock stocks.sum(:amount) end def stock=(stock_value) self.save stock_delta = stock_value - self.stock if stock_value >=0 and (stock_delta!=0) self.stocks.create(amount: stock_delta) end end |
Positioning vertical rotated text with flexbox Posted: 05 Jun 2016 12:44 AM PDT I am trying to put a y-axis label on a figure. The html code is <div class="figure"> <%= render 'graphs/overview_graph_no_time', graph: @graph %> <div class='y_label'> <p class="y_label_text">Some Label</p> </div> </div> and the scss is .figure{ display: flex; flex-direction: row-reverse; .y_label{ margin-right: auto; margin-left: auto; max-width: 30px; .y_label_text{ transform: rotate(-90deg); font-weight: bold; } } } The 'Some Label' text should be on one line, and vertically centered, and the width of the containing div should be thinner. Instead, the 'Some Label' text is split into two lines, is at the top an the width of the containing div is too wide (see picture) |
ng-token-auth Registration promise not resolving with rails Posted: 05 Jun 2016 12:36 AM PDT I have managed to set up ng-token-auth with ionic(angular) and devise-token-auth with rails however when I create a User no error is logged in the rails console and the the user is created. The user is created in the database however I have designed the ionic user controller to login the user once the registration is complete by using a promise. The controller is below: comeDineApp.controller('userController', ['ipCookie','$scope', '$state', '$auth', function(ipCookie, $scope, $state, $auth){ $scope.handleRegBtnClick = function() { console.log("hello") $auth.submitRegistration($scope.registrationForm) .then(function() { console.log("welcome") $auth.submitLogin({ email: $scope.registrationForm.email, password: $scope.registrationForm.password }); }); }; }]); In this case the submitLogin function doesn't execute as the promise is not resolved even though the user is successfully created in the DB. My rails user model is below: class User < ActiveRecord::Base # Include default devise modules. devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :omniauthable include DeviseTokenAuth::Concerns::User has_many :tables before_save -> do self.uid = SecureRandom.uuid skip_confirmation! end end and my user controller is: class UsersController < ApplicationController before_action :authenticate_user! respond_to :json def show render json: current_user.tables end end Any ideas how I can resolve this either in the rails or the angular so that the angular promise resolves to login directly after signing up? |
Store hash values in url Posted: 05 Jun 2016 12:58 AM PDT Rails 5.0.0.rc1 Ruby 2.2.5 (can update to latest) I'd like to think this is possible. I'm making a get request that when a field is selected then the user presses the next button, it goes to another page and that page's url looks like: http://localhost:3000/food/r/new?utf8=%E2%9C%93&id=2&food=Apple&commit=Next This looks ugly, to me. Could it be more nicer to look like this: http://localhost:3000/food/r/new/<some_random_short_string/<name-of-page> I'd imagine the some_random_short_string would be a hash then in the controller would have something like: hash = params[:some_random_short_string] hash[:food] #=> "Apple" etc... Not sure how to go about this. Any pointers, please? |
carrierwave uploader params not permitting [on hold] Posted: 04 Jun 2016 11:59 PM PDT parameters Parameters: {"utf8"=>"✓", "bid"=>{"type_name"=>"Separate Bid", "check_bid"=>"true", "agree_with_tos"=>"true"}, "buyers_premium_perc"=>"", "bid_amount_a0H210000000T0sEAE"=>"$1.00", "item_in_bids"=>[{"bid_amount"=>"1", "item_id"=>"a0H210000000T0sEAE"}], "buyer"=>"", "bid_percent_a0H210000000T0sEAE"=>"0.0000%", "buyer_premium_a0H210000000T0sEAE"=>"$0.05", "total_bid_a0H210000000T0sEAE"=>"$1.05", "item_in_bid"=>{"attachment"=>#, @original_filename="Screenshot from 2016-05-10 14:26:22.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"item_in_bid[attachment]\"; filename=\"Screenshot from 2016-05-10 14:26:22.png\"\r\nContent-Type: image/png\r\n">, "is_residential"=>"false"}} and def Item_params @item_params = @params.require(:item_in_bids).map{|v| ActionController::Parameters.new(v).permit(:bid_amount, :item_id, :item_in_bids => [:attachment])} @item_params.sort!{|a,b| a[:item_id] <=> b[:item_id]} @item_params end |
Counting in jbuilder throw exeption Posted: 04 Jun 2016 11:57 PM PDT json.votes answer, answer.votes.count throw 0 is not a symbol nor a string Also try json.votes answer, answer.votes.count.to_s throw undefined method '0' for #<Answer:0x00000004699a98> Application code |
Error "param is missing or the value is empty: personas_x_tipos_persona" Posted: 05 Jun 2016 12:17 AM PDT I'm starting in rails and I have this error that I'm not able to solve.. Error - param is missing or the value is empty: personas_x_tipos_persona Controller class PersonasController < ApplicationController def create_cliente @cliente = Persona.new(persona_params) @personas_x_tipos_personas = Persona.new(tipos_personas_params) if @cliente.save redirect_to show_clientes_path else render :new_cliente end end private def persona_params params.require(:persona).permit(:nombre, :apellido, :direccion, :ruc, :contacto, :email) end def tipos_personas_params params.require(:personas_x_tipos_persona).permit(:linea_credito) end end view <div> <%= form_for :persona ,:url => add_cliente_path, :html => {:method => :post} do |f|%> <% @cliente.errors.full_messages.each do |message| %> <div class="alert alert-danger" margin-top:10px"> * <%=message%> </div> <% end %> <%= f.text_field :nombre, placeholder: "Nombre del Cliente"%> <%= f.text_field :apellido, placeholder: "Apellido del Cliente"%> <%= f.text_field :direccion, placeholder: "Direccion del Cliente"%> <%= f.text_field :ruc, placeholder: "RUC del Cliente"%> <%= f.text_field :contacto, placeholder: "Contacto del Cliente"%> <%= f.email_field :email, placeholder: "Email del Cliente""%> <%= f.fields_for :personas_x_tipos_persona do |pxp|%> <%= pxp.number_field :linea_credito, placeholder: "Linea de Credito del Cliente"%> <% end %> <%= f.submit 'Guardar'%> <% end %> </div> |
"http" directive is not allowed here in /etc/nginx/conf.d/proxy.conf "rails" Posted: 05 Jun 2016 04:02 AM PDT Im getting a an error in my nginx error log. Im trying to add increase file size by adding a folder called .ebextensions and adding a file called 01_files.config. something to do with the http {} im not really sure how to update this file to make it work!! thanks!! In my 01_files.config files: "/etc/nginx/conf.d/proxy.conf" : mode: "000755" owner: root group: root content: | http { client_max_body_size 20M; } service nginx reload image.config "located in the .ebextensions folder" packages: yum: ImageMagick-devel: [] /var/log/nginx/error.log 2016/06/05 03:23:01 [emerg] 6587#0: "http" directive is not allowed here in /etc/nginx/conf.d/proxy.conf:1 /var/log/nginx/error.log-20160605 [error] 2818#0: *19636 client intended to send too large body: 2771652 bytes, client: 172.31.24.171, server: _, request: "POST / HTTP/1.1", host: |
Wepay Benifieciary account issue Posted: 04 Jun 2016 11:13 PM PDT I am using this API or Beneficiary account with Wepay /account/membership And I am getting auth error, While i have register this account. Please tell me which API i have to use to solve this problem. |
nested_attributes save parent first Posted: 05 Jun 2016 03:12 AM PDT i had 2 models. User and Company Company class Company < ActiveRecord::Base has_many :users, dependent: :destroy validates :name, presence: true, uniqueness: true accepts_nested_attributes_for :users end User class User < ActiveRecord::Base belongs_to :company validates :name, presence: true validates :company, presence: true end And i got a Hash: {:name=>"My Company", :users_attributes=>[{:name=>"My User"}]} Now i run the following: params = {:name=>"My Company", :users_attributes=>[{:name=>"My User"}]} company = Company.new params company.save The behaviour is what i'm expected. company could not saved, because the User is not valid (validation: validates :company, presence: true ) for this, i used everytime a concern class which does the following: - create company
- create users for this company
so my question is: Is it possible to save first the parent, and when valid save the childrens as an second part, without using a concern class? does exist for this situation a rails way like "accepts_nested_attributes_and_save_first_parent_for"? |
No comments:
Post a Comment