Rails / Devise / Omniauth combo says email is nil but it's not Posted: 07 Jan 2017 07:23 AM PST I was setting up Devise & Omniauth as per railscasts like I usually do, only now I'm using Rails 5.0.1 and ruby 2.3.3 When I go to add a user, not even using Omniauth, just using a basic email + password + confirmation the page reloads with an error of "Email can't be blank". I can see the parameters include the email. I used Pry to investigate - things get weird here. [1] pry(#<RegistrationsController>)> params => <ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"[removed this!]", "user"=><ActionController::Parameters {"email"=>"test@test.com", "password"=>"testtest", "password_confirmation"=>"testtest"} permitted: false>, "commit"=>"Sign up", "controller"=>"registrations", "action"=>"create"} permitted: false> [3] pry(#<RegistrationsController>)> @user => #<User id: nil, email: "test@test.com", created_at: nil, updated_at: nil, first_name: nil, last_name: nil, image_url: nil, headline: nil, dob: nil, gender: nil, webpage_url: nil, twitter: nil, linkedin: nil, blog_url: nil, description: nil, country: nil, state: nil, city: nil, phone: nil, full_bio: nil, profile_claimed: nil> [4] pry(#<RegistrationsController>)> @user.class => User(id: integer, email: string, encrypted_password: string, reset_password_token: string, reset_password_sent_at: datetime, remember_created_at: datetime, sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: datetime, current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime, updated_at: datetime, first_name: string, last_name: string, image_url: string, headline: string, dob: date, gender: string, webpage_url: string, twitter: string, linkedin: string, blog_url: string, description: text, country: string, state: string, city: string, phone: string, full_bio: text, type: string, profile_claimed: boolean) [5] pry(#<RegistrationsController>)> @user.email => nil [7] pry(#<RegistrationsController>)> @user.errors => #<ActiveModel::Errors:0x007f9de2c82da0 @base= #<User id: nil, email: "test@test.com", created_at: nil, updated_at: nil, first_name: nil, last_name: nil, image_url: nil, headline: nil, dob: nil, gender: nil, webpage_url: nil, twitter: nil, linkedin: nil, blog_url: nil, description: nil, country: nil, state: nil, city: nil, phone: nil, full_bio: nil, profile_claimed: nil>, @details={:email=>[{:error=>:blank}, {:error=>:blank}]}, @messages={:email=>["can't be blank"], :password=>[], :password_confirmation=>[]}> [8] pry(#<RegistrationsController>)> @user.email.class => NilClass You can see that if I access @user it returns the hash containing the email. However if I try @user.email I get nil. And when I ask for @user.errors the message says email can't be blank. I've been hunting a while on this one. Thanks in advance for any help! |
Building fixtures using associations aliases Posted: 07 Jan 2017 07:14 AM PST When I try to build my fixtures using rails db:fixtures:load I get the error message ActiveRecord::Fixture::FixtureError: table "spec_rows" has no column named "multipliers". The issue I believe is stemming from the fact that I'm using alias associations/custom named associations (name for this?). I am using Rails 5.0.1. My models look like this: class SpecRow < ApplicationRecord has_many :multipliers, class_name: 'SpecValue', foreign_key: 'multiplier_id' has_one :total_value, class_name: 'SpecValue', foreign_key: 'total_value_id' end class SpecValue < ApplicationRecor belongs_to :multiplier, class_name: 'SpecRow', foreign_key: 'multiplier_id', optional: true belongs_to :total_value, class_name: 'SpecRow', foreign_key: 'total_value_id', optional: true end with the following schema ActiveRecord::Schema.define(version: 20170107140315) do enable_extension "plpgsql" create_table "spec_rows", force: :cascade do |t| t.string "title" t.integer "spec_value_reference_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "spec_values", force: :cascade do |t| t.decimal "amount" t.integer "multiplier_id" t.integer "total_value_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_foreign_key "spec_values", "spec_rows", column: "multiplier_id" add_foreign_key "spec_values", "spec_rows", column: "total_value_id" end Then I got the fixture test/fixtures/spec_values.yml : n_persons: amount: 16 n_meetings: amount: 4 price: amount: 40 ok_total_value: amount: 2000 and the fixture the fixture test/fixtures/spec_rows.yml : nollu: title: Mötesmat NollU multipliers: [n_persons, n_meetings, price] ok: title: Mötesmat OK total_value: ok_total_value What am I missing? Why doesn't the fixture want to load? |
How to hide form upon submit? Posted: 07 Jan 2017 07:26 AM PST When a user submits, how can we hide the respective form? <% @challenge.dates_challenged.first(@challenge.days_challenged + @challenge.missed_days).each_with_index do |date, i| %> <div id="show-all-notes"> # upon submit the text appears here, javascript magic </div> <div class="notes-form-background"> DAY <%= i + 1 %> <%= date.strftime("%b %d, %Y") %> <%= form_for [@notable, @note], remote: true do |f| %> <%= f.text_area :notes_text %> <%= f.submit, class: "btn" %> <% end %> </div> <% end %> <script> $(document).ready(function(){ $('.btn').click(function(){ $('form').toggle(); }); }); </script> With something like the script I have though it removes all iterations of the form, not just the one submitted. Is there maybe a way to use Day <%= i + 1 %> to uniquely identify each form so that only the form that is submitted is hidden? |
rails form_tag doesn't work anymore Posted: 07 Jan 2017 07:11 AM PST Surprisingly i can't make this simple form_tag to send me the params.. for an hour.. It worked on my last project. I did a copy of it, used different Ruby version and now it doesn't work. Tried many things but it just don't work. I have this block: <div class="row"> <div class="col-md-8"> <div id="light-pagination" class="pagination"></div> </div> <div class="col-md-4" style='float:right'> <%= form_tag("/go_to_show_question", class: "form-inline", method: "get") do %> <%= hidden_field_tag(:id, @question_group.id) %> <%= search_field_tag :question, '', size: 5, class: 'form-control' %> <%= submit_tag r("tests.go_to_question"), class: 'btn btn-default' %> <% end %> </div> </div><br> I am inputting a number and clicking on 'Go to question'. And it sends only: {"controller"=>"question_groups", "action"=>"go_to_show_question", "locale"=>"en"} Where is 'id' and 'question'? why they are not sent together? I believe this is something stupid but i cant find what.. It worked before. I didnt change it i believe. This is the generated HTML <div class="row"> <div class="col-md-8"> <div id="light-pagination" class="pagination"></div> </div> <div class="col-md-4" style='float:right'> <form class="form-inline" action="/go_to_show_question" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓" /> <input type="hidden" name="id" id="id" value="28" /> <input type="search" name="question" id="question" value="" size="5" class="form-control" /> <input type="submit" name="commit" value="Go to question" class="btn btn-default" /> </form> </div> </div><br> Routes: Rails.application.routes.draw do ... other routes ... scope ":locale", locale: /#{I18n.config.available_locales.join("|")}/ do ... other routes ... get 'go_to_show_question' => 'question_groups#go_to_show_question' ... other routes ... end get '*path', to: redirect("/#{(I18n.locale)}/%{path}"), constraints: lambda { |req| !req.path.starts_with? "/#{I18n.locale}/" } match '', to: redirect("/#{(I18n.locale)}"), via: [:get, :post, :put, :delete] end Controller: class QuestionGroupsController < ApplicationController def go_to_show_question redirect_to show_question_group_path(:id => params[:id], :question => (params[:question].to_i - 1)) end end This request reaches my controller. but without id, question params. And this is the Log Processing by QuestionGroupsController#go_to_show_question as HTML Parameters: {"locale"=>"en"} User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1 {"controller"=>"question_groups", "action"=>"go_to_show_question", "locale"=>"en"} Redirected to http://localhost:3000/en/show_question_group?question=-1 Completed 302 Found in 2ms (ActiveRecord: 0.2ms) |
Rails 5 Test Database Creation Posted: 07 Jan 2017 06:45 AM PST I have a task to create certain extensions in PostgreSQL database. In Rails 5, the following task does not execute for "test" database. # lib/tasks/db_enhancements.rake namespace :db do desc 'Also create shared_extensions Schema' task :extensions => :environment do # Create Schema ActiveRecord::Base.connection.execute 'CREATE SCHEMA IF NOT EXISTS shared_extensions;' # Enable Hstore ActiveRecord::Base.connection.execute 'CREATE EXTENSION IF NOT EXISTS HSTORE SCHEMA shared_extensions;' # Enable UUID-OSSP ActiveRecord::Base.connection.execute 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp" SCHEMA shared_extensions;' # Enable Postgis # Drop the postgis extension first ActiveRecord::Base.connection.execute 'DROP EXTENSION "postgis"'; # Create postgis in shared_extensions ActiveRecord::Base.connection.execute 'CREATE EXTENSION IF NOT EXISTS "postgis" SCHEMA shared_extensions;' end end Rake::Task["db:create"].enhance do Rake::Task["db:extensions"].invoke end Rake::Task["db:test:purge"].enhance do Rake::Task["db:extensions"].invoke end |
wrong format in request saving images Posted: 07 Jan 2017 06:58 AM PST I whant to load images in form . Here is my controller create action def create @place = Place.new(place_params) respond_to do |format| if @place.save params[:place_attachments]['image'].each do |i| @place_attachment = @place.place_attachments.create!(:image => i, :place_id => @place.id) end format.json { render json: { place: @place, message: 'Placement created!', status: 201 } } end end end protected def check_existance @place = Place.find_by_address(params[:place][:address]) if @place respond_to do |format| format.js {render 'create', place: @place} end end end check_existance is a before_action filter. here is a form that i'm using =form_for Place.new, html: { multipart: true }, remote: true do |f| div = f.label :address, class: 'label_hidden' = f.text_field :address, class: "form-control" div = f.label :title, class: 'label_hidden' = f.text_field :title, class: "form-control" div = f.label :longitude, class: 'label_hidden' = f.text_field :longitude, class: "form-control" div = f.label :latitude, class: 'label_hidden' = f.text_field :latitude, class: "form-control" = f.fields_for PlaceAttachment.new do |p| = p.label :image br = p.file_field :image, :multiple => true, name: "place_attachments[image][]" div = f.submit 'Create', class: "btn btn-default" but when im trying to create a place I recieve ActionController::UnknownFormat in PlacesController#create Sorry for my english, if you need some more details? please let me know. I need help to get through this. Would be grateful for any advise |
Rails 4: Reload page with ajax after submitting remote form to a different controller Posted: 07 Jan 2017 06:18 AM PST I've made a comments section for my 'posts' views and I've got remote: true working on the form so when you hit enter and submit the 'new comment' form to the database, it updates in the background fine (the comment is created, page doesn't redirect or change) but I can't get it to load the comments on the page. You have to refresh the page to see them. I could do redirect_to :back in the comments controller after saving but that takes user to top of the page rather than staying put to see the comment appear. I've tried render 'posts#show' after saving the comment in the comment controller create action but that tries to send you to /comments/posts/:slug/ . If it actually rendered the posts show action I think this would work. Comments controller: class CommentsController < ApplicationController before_action :find_commentable def show end def new @comment = Comment.new end def create @comment = @commentable.comments.new comment_params @comment.author = current_user if current_user @comment.save end private def comment_params params.require(:comment).permit(:body, :author_id, :post_id) end def find_commentable @commentable = Comment.find(params[:comment_id]) if params[:comment_id] @commentable = Post.find_by_slug(params[:post_id]) if params[:post_id] end end Comment section on post show view: %ul#post-comments = render 'comment_feed' = form_for [@post, Comment.new], remote: true do |f| = f.text_field :body, class: 'js-new-comment-field', placeholder: "Write a comment..." posts/show.js.erb: $("#post-comments").html("<%= escape_javascript render("comment_feed") %>"); Routes.rb: resources :posts do collection do match 'search' => 'posts#search', via: [:get, :post], as: :search # For ransack search end resources :comments end resources :comments do resources :comments # Replies on comments end |
best framework to build a music download web application? Posted: 07 Jan 2017 06:05 AM PST I am looking to build a web application that allows people to download music from my website, what is the best framework I can use? Or how can I go about doing that> |
Rails Form Check Box or select Array value for multiple arrays Posted: 07 Jan 2017 05:47 AM PST I'm maintaining a Rails 3.2.22.5 legacy app and creating a form to send messages internally to users (in this case they are called medics). Here is what my form currently looks like. <%= form_for(@mass_message, url: '/mass_messaging', method: 'post') do |f| %> <%= f.text_field :subject, placeholder: "Subject" %> <%= f.text_area :body, placeholder: "Body of message"%> <%= f.label :medic %> <%= f.select(:medic_ids, medic_select, {}, {:multiple => true, :class => 'select'}) %> <%= f.button "Submit" %> <% end %> This works fine but I'd like to be able to shovel groups of Medics by a division column into the medic_ids array on the object. From the console when I do the following: m = MassMessage.new m.medic_ids = Medic.where(division: "Dallas").map {|medic| medic.id} m.save It will get the ids that are mapped from the where clause and inject them into the medic_ids array properly and create the record in a join table called MassMessageMedic properly. However, in this form I need the ability to create some sort of selector or even checkboxes in the form to select the different divisions of which there are 4. So this is a two part question really 1.) Given these four statements (divisions) Medic.where(division: "Dallas").map {|medic| medic.id} Medic.where(division: "Houston").map {|medic| medic.id} Medic.where(division: "Beaumont").map {|medic| medic.id} Medic.where(division: "Texoma").map {|medic| medic.id} How can I construct these into some sort of helper method that would allow each array to be selected (one or multiple) and injected into the medic_ids array? I'm trying different things and thinking a helper method called medic_select might be the answer but I'm hitting a wall with how to create this selector which will essentially be an array of arrays if I'm not mistaken. 2.) Given the above arrays how could I instead of a selector in the form use a check_box to define that when the checkbox is clicked the proper medics are selected by division. Here is an example I tried but I'm receiving an error: <%= f.label :houston %> <%= f.check_box :medic_ids, Medic.where(division: "Houston").map {|medic| medic.id} %> <%= f.label :dallas %> <%= f.check_box :medic_ids, Medic.where(division: "Dallas").map {|medic| medic.id} %> The error I receive is: undefined method merge' for #` when trying to do it this way. I'm pretty sure this can be done, but after an hour of searching and trying different things I'm really no further than when I began. I'm hoping someone can point me in the right direction on this one. In the meantime I will continue to Google and research Stack to see if someone else had a similar issue. If my code and/or question is not concise or clear please let me know and I will edit. |
how to create an auto increment field that is generated automatically. am using ruby on rails Posted: 07 Jan 2017 05:26 AM PST this is my model i want employeecode to be generated automatically and must auto increment: schema. ActiveRecord::Schema.define(version: 20170106130651) do create_table "add_employees", force: :cascade do |t| t.string "Name" t.string "Surname" t.integer "Employeecode" t.string "Email" t.integer "Phonenumber" t.string "Gender" t.string "Employeestatus" t.string "Position" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "Title" end model: class AddEmployee < ApplicationRecord before_create :set_code def set_code max_code = Operation.maximum(:Employeecode) self.code = max_code.to_i + 1 auto_increment :Employeecode end |
Angularjs with rails API rest post 400 (bad request) Posted: 07 Jan 2017 05:53 AM PST Hello i making a project of rails api and angularJs,And I found the following error. angular.js:11821 POST http://localhost:3000/people 400 (Bad Request) And I could not find why. code below. Rails Controller # POST /people def create @person = Person.new(person_params) if @person.save render json: @person, status: :created, location: @person else render json: @person.errors, status: :unprocessable_entity end end AngularJS $scope.SendData = function () { // use $.param jQuery function to serialize data from JSON var data = $.param({ name: $scope.name, age: $scope.age, gender:$scope.gender, lonlat:$scope.lonlat }); var config = { headers : { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' } } $http.post('http://localhost:3000/people', data, config) .then(function (data, status, headers, config) { $scope.PostDataResponse = data; }) .catch(function (data, status, header, config) { $scope.ResponseDetails = "Data: " + data + "<hr />status: " + status + "<hr />headers: " + header + "<hr />config: " + config; }); }; Html <div ng-app="myApp" ng-controller="person"> <div class="modal-body"> <div class="form-group"> <label for="exampleInputEmail1">Name:</label> <input type="text" class="form-control" name="name" ng-model="name" placeholder="Email"> </div> <div class="form-group"> <label for="exampleInputEmail1">age:</label> <input type="text" class="form-control" name="age" ng-model="age" placeholder="Email"> </div> <div class="form-group"> <label for="exampleInputEmail1">gender:</label> <input type="text" class="form-control" name="gender" ng-model="gender" placeholder="Email"> </div> <div class="form-group"> <label for="exampleInputEmail1">lonlat:</label> <input type="text" class="form-control" name="lonlat" ng-model="lonlat" placeholder="Email"> </div> <button ng-click="SendData()" class="btn btn-default">Submit</button> {{ PostDataResponse }} thanks for listening |
What kind of storage to use in order to keep track of logs and process them fast? Posted: 07 Jan 2017 04:05 AM PST In a big Rails application on a server, what kind of storage should I use in order to keep track of system and custom logging data that I could access in real time and extract reports or calculate new parameters ? For example, I am running a service that tracks system's resources e.g. CPU, temperature etc. and I want to keep the values I request every 5 seconds in a database or file. I also want to call a function that will run calculations (time, max/min, relations to other readings etc.) and output some results. So we're talking about fast r/w. Log files appear to be difficult to manage and the only solution that seems suitable to me is using a NoSQL database e.g. Redis. What do you do in similar cases? |
Mysql to mariadb with ruby on MacOS Posted: 07 Jan 2017 03:44 AM PST I've switched to mariadb few days ago. When I tried to start my ruby project, I got /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/mysql2-0.3.20/lib/mysql2.rb:31:in `require': dlopen(/Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/mysql2-0.3.20/lib/mysql2/mysql2.bundle, 9): Library not loaded: /usr/local/opt/mysql/lib/libmysqlclient.20.dylib (LoadError) Referenced from: /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/mysql2-0.3.20/lib/mysql2/mysql2.bundle Reason: image not found - /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/mysql2-0.3.20/lib/mysql2/mysql2.bundle from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/mysql2-0.3.20/lib/mysql2.rb:31:in `<top (required)>' from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/bundler-1.13.5/lib/bundler/runtime.rb:91:in `require' from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/bundler-1.13.5/lib/bundler/runtime.rb:91:in `block (2 levels) in require' from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/bundler-1.13.5/lib/bundler/runtime.rb:86:in `each' from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/bundler-1.13.5/lib/bundler/runtime.rb:86:in `block in require' from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/bundler-1.13.5/lib/bundler/runtime.rb:75:in `each' from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/bundler-1.13.5/lib/bundler/runtime.rb:75:in `require' from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/bundler-1.13.5/lib/bundler.rb:106:in `require' from /Users/user_name/Desktop/localhost/project_name/config/application.rb:9:in `<top (required)>' from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/railties-3.2.22.5/lib/rails/commands.rb:53:in `require' from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/railties-3.2.22.5/lib/rails/commands.rb:53:in `block in <top (required)>' from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/railties-3.2.22.5/lib/rails/commands.rb:50:in `tap' from /Users/user_name/.rvm/gems/ruby-2.0.0-p648@project_name/gems/railties-3.2.22.5/lib/rails/commands.rb:50:in `<top (required)>' from script/rails:8:in `require' from script/rails:8:in `<main>' I believe that the gem must be reinstalled to match the correct path to the db. I'm not sure how this works. Any help appreciated. I have to add that the production of this product doesn't use mariadb. |
AWS Cognito not sending verification SMS Posted: 07 Jan 2017 03:39 AM PST I have setup AWS cognito with my own user pool, but when i create a user with a valid phone number i did not receive verification SMS on that phone. I have also created role to allow Amazon Cognito to send SMS messages. Please help me to debug the issue. |
Ruby Gem Install MySQL Error Posted: 07 Jan 2017 03:59 AM PST I have a problem with an install of mysql gem. This is my error : gem install mysql -v '2.9.1' Building native extensions. This could take a while... ERROR: Error installing mysql: ERROR: Failed to build gem native extension. current directory: /usr/local/rvm/gems/ruby-2.4.0/gems/mysql-2.9.1/ext/mysql_api /usr/local/rvm/rubies/ruby-2.4.0/bin/ruby -r ./siteconf20170107-4120-x2dv85.rb extconf.rb checking for mysql_ssl_set()... yes checking for rb_str_set_len()... yes checking for rb_thread_start_timer()... no checking for mysql.h... yes creating Makefile To see why this extension failed to compile, please check the mkmf.log which can be found here: /usr/local/rvm/gems/ruby-2.4.0/extensions/x86_64-linux/2.4.0/mysql-2.9.1/mkmf.log current directory: /usr/local/rvm/gems/ruby-2.4.0/gems/mysql-2.9.1/ext/mysql_api make "DESTDIR=" clean current directory: /usr/local/rvm/gems/ruby-2.4.0/gems/mysql-2.9.1/ext/mysql_api make "DESTDIR=" compiling mysql.c mysql.c: In function 'stmt_bind_result': mysql.c:1320:74: error: 'rb_cFixnum' undeclared (first use in this function) else if (argv[i] == rb_cNumeric || argv[i] == rb_cInteger || argv[i] == rb_cFixnum) ^ mysql.c:1320:74: note: each undeclared identifier is reported only once for each function it appears in mysql.c: At top level: cc1: warning: unrecognized command line option "-Wno-self-assign" cc1: warning: unrecognized command line option "-Wno-constant-logical-operand" cc1: warning: unrecognized command line option "-Wno-parentheses-equality" cc1: warning: unrecognized command line option "-Wno-tautological-compare" Makefile:241: recipe for target 'mysql.o' failed make: *** [mysql.o] Error 1 make failed, exit code 2 Gem files will remain installed in /usr/local/rvm/gems/ruby-2.4.0/gems/mysql-2.9.1 for inspection. Results logged to /usr/local/rvm/gems/ruby-2.4.0/extensions/x86_64-linux/2.4.0/mysql-2.9.1/gem_make.out When i try this command "sudo gem install mysqlv -v '2.9.1', it's works, and i read this line to justify it... sudo gem install mysql -v '2.9.1' Building native extensions. This could take a while... Successfully installed mysql-2.9.1 Parsing documentation for mysql-2.9.1 Done installing documentation for mysql after 0 seconds 1 gem installed I don't understand what happened and how to solved this. If someone could help me... Thanks in advance ! Christophe |
Select records with less than N associations that do not have particular association Posted: 07 Jan 2017 03:56 AM PST I have following models: class Rating < ApplicationRecord belongs_to :user belongs_to :image validates :image_id, uniqueness: { scope: [ :user_id] } end class Image < ApplicationRecord has_many :ratings, dependent: :destroy has_many :users, through: :ratings end class User < ApplicationRecord has_many :ratings, dependent: :destroy has_many :images, through: :ratings end Users are rating the images. I want to get the images that are not rated by a particular user, and that are rated by less than 3 users in total. Right now I'm showing those images that are rated by minimal number of user. I've done this with cache counter: @image = Image.order(:ratings_count).first Part I'm having problems with is how to get the Images that are not rated by current user. Would appreciate any help. Number of queries is not that important, as long as it's the Ruby Way to get this records. |
seatgeek api pulling events out of hash in array in json Posted: 07 Jan 2017 03:19 AM PST i'm having trouble pulling events from the seat geek api. I can pull a title when giving an id for instance https://api.seatgeek.com/2/events/3475509 "links": [], "in_hand": {}, "id": 3475509, "stats": { "listing_count": 401, "average_price": 133, "lowest_price_good_deals": 71, "lowest_price": 71, "highest_price": 932 }, "title": "Toronto Raptors at Chicago Bulls" i can pull the title out like so: require 'Unirest' @events = [] @events << Unirest.get("https://api.seatgeek.com/2/events/3475509?&client_id=////").body @events.each do |event| puts event["title"] end which returns the title of the event I get that but when I make a call to the seatgeek api and try to return mutliple events in a given area I'm having trouble for instance:https://api.seatgeek.com/2/events?datetime_utc.gt=2017-01-07&datetime_utc.lte=2017-01-30&geoip=104.18.37.48&range=20mi&client_id=NjQwNTEzMXwxNDgxNDkxODI1 which retunrs this displays every event in san fran betweens these dates what I would like to do is pull out each event from this. here is what I have so far require 'Unirest' @events = Unirest.get("https://api.seatgeek.com/2/events?datetime_utc.gt=2017-01-07&datetime_utc.lte=2017-01-08&geoip=104.18.37.48&range=20mi&client_id=NjQwNTEzMXwxNDgxNDkxODI1").body @c = @events["events"] @c[0..9].each do |event| p event["title"] end its only returning 2 titles rather then 10 not sure why I'm not getting an error anymore at least any help would be much appreciated! |
Actioncable settings when not using Devise for authentication Posted: 07 Jan 2017 02:16 AM PST Normally if you're using devise, you can do current_user = env['warden'].user in the connection.rb file , but when you create your own authentication from scratch...what would it be? channels/application_cable/connection.rb module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user def connect self.current_user = find_verified_user logger.add_tags "ActionCable", "User #{current_user.id}" end protected def find_verified_user if current_user = env['warden'].user current_user else reject_unauthorized_connection end end end end |
heroku assets:precompile error for foundation sites $color Posted: 07 Jan 2017 02:15 AM PST I have an "angular of rails" app using foundation-sites which I'm installing with bower. Whenever I try to push to heroku, it breaks on running rake assets:precompile with the following error: remote: rake aborted! remote: Sass::SyntaxError: $color: "foreground(#09798e)" is not a color for `red' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/assets/bower_components/foundation-sites/scss/util/_color.scss:19:in `foundation-badge' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/app/assets/stylesheets/foundation_and_overrides.scss:21 remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/app/assets/stylesheets/cguides.scss:1 remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/bundle/ruby/2.3.0/gems/sass-3.4.22/lib/sass/script/tree/funcall.rb:310:in `reformat_argument_error' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/bundle/ruby/2.3.0/gems/sass-3.4.22/lib/sass/script/tree/funcall.rb:149:in `rescue in _perform' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/bundle/ruby/2.3.0/gems/sass-3.4.22/lib/sass/script/tree/funcall.rb:123:in `_perform' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/bundle/ruby/2.3.0/gems/sass-3.4.22/lib/sass/script/tree/node.rb:58:in `perform' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/bundle/ruby/2.3.0/gems/sass-3.4.22/lib/sass/script/tree/list_literal.rb:63:in `block in _perform' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/bundle/ruby/2.3.0/gems/sass-3.4.22/lib/sass/script/tree/list_literal.rb:63:in `map' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/bundle/ruby/2.3.0/gems/sass-3.4.22/lib/sass/script/tree/list_literal.rb:63:in `_perform' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/bundle/ruby/2.3.0/gems/sass-3.4.22/lib/sass/script/tree/node.rb:58:in `perform' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/bundle/ruby/2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/perform.rb:471:in `visit_variable' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/bundle/ruby/2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/base.rb:36:in `visit' remote: /tmp/build_2017bed0c047fd92960507e2e0ee8a54/vendor/bundle/ruby/2.3.0/gems/sass-3.4.22/lib/sass/tree/visitors/perform.rb:160:in `block in visit' ... However, when I run RAILS_ENV=production bundle exec rake assets:precompile locally, it goes through with no glitch, making the situation totally confusing to me. In my bower.json file, I have: "foundation-sites": "latest", Suffice it to say however, that when I entered heroku bash and checked the contents of vendor/assets/bower_components/foundation-sites/scss/util/_color.scss , it's slightly different from my local version. but no mention of the complained $color: "foreground(#09798e)" in the file. At the moment, I'm resigned to precompiling the assets locally before push, but it's getting too cumbersome and I need to figure this out. Thanks. |
How to load sub categories with categories in rails Posted: 07 Jan 2017 03:57 AM PST I am using simple for display multi select forms <%= simple_form_for(@shopify_store,:html => { :multipart => true }) do |f| %> to save many to many records in a junction table (with has_and_belongs_to_many association) and I have used association to display these attributes <div class="field"> <%= f.label :store_category_id %> <%= f.collection_select :store_category_id, StoreCategory.all, :id, :name %> </div> <%= f.association :sub_categories, as: :check_boxes %> How can I get only those sub categories that are related to categories and how can I get all value back in controller I tried to use this gem jquery-ui-multiselect-widget but didn't get it. In image all the data from sub-categories displayed I only want to display select category -> sub categories . |
Send_data returning corrupted files Posted: 07 Jan 2017 12:15 AM PST I have the following download action in my resources controller: def download require 'open-uri' if validate_token(safe_params[:x]) resource = Resource.find_by_token(safe_params[:x]) data = open(resource.file.url) send_data( data, :disposition => 'attachment',:url_based_filename => true, type: data.meta['content-type'].to_s) # send_file data, disposition: 'attachment' # redirect_to resource.file.url puts data.hash puts data.meta['x-goog-hash'] else redirect_to pages_error_path, notice: 'Does not match resource.' end end The action downloads a file stored on Google Storage (using carrierwave ) and then streams that file to the browser. I tried multiple different configurations of the parameters to send_data and I tried send_file as well. The closest I have come to a working solution is where a PDF file is downloaded but it is corrupt. (Sometimes it accidentally downloads a text document, and rather than the expected file contents I get the memory object of the file as shown below. #<File:0x007fcdda128ea0> I have a feeling the same happens with the PDF download, except that the PDF viewer obviously cannot render that PDF. I made sure that the URL stored in the database does point to the correct file and the data variable is initialized correctly. Everything works as expected up until the point where the data is sent to the browser. The reason I do this rather than redirecting to the file url is because i dont want to expose the file location on Google storage to the user (hence the temporary download to the server) |
Disable Sign Up for ActiveAdmin Posted: 06 Jan 2017 11:53 PM PST I'd like to disable sign up for ActiveAdmin and not just removing the link the Sign In page. Can that be done? Thanks |
How to Render a Enquery form in a product show page Posted: 07 Jan 2017 04:17 AM PST I Have a product's show page which displays the information about the product. I also have an enquery form on the same show page, so the user can send an enquery regarding the product.The enquery data has to be saved into the Enquery model with a corresponding EnqueresController which should have index and show actions. How can this be done in Rails? Any help is highly appreciated. Thanks in Advance! @product = Product.find(params[:id]) @enquery = Enquery.where("product_id = ?",@product.id).present? |
PG::UndefinedTable ERROR ruby on rails heroku Posted: 06 Jan 2017 11:28 PM PST I have been getting my application ready for production, and I am struggling with raking my database. It is giving me this error: PG::UndefinedTable: ERROR: relation "events" does not exist : ALTER TABLE "events" ADD "code" character varying Here is my database.yml file: # SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' # default: &default adapter: postgresql pool: 5 timeout: 5000 development: <<: *default database: db/development.sqlite3 production: <<: *default database: db/production.postgresql Here is my events migration file: class CreateEvents < ActiveRecord::Migration[5.0] def change create_table :events do |t| t.string :name t.string :partycode t.references :user, foreign_key: true t.timestamps end end end EDIT: when I run rake db:migrate:status I get the following result: Finally, here is my gemfile: source 'http://rubygems.org' gem 'bootstrap-sass', '3.2.0.2' gem 'bcrypt', '3.1.11' gem 'will_paginate' gem 'responders' gem 'rails', '~> 5.0.0', '>= 5.0.0.1' gem 'puma', '~> 3.0' gem 'sass-rails', '~> 5.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.2' gem "heroku" gem 'coffee-script-source', '1.8.0' gem 'jquery-rails' gem 'turbolinks', '~> 5' gem 'jbuilder', '~> 2.5' group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'sqlite3' gem 'byebug', platform: :mri end group :production do gem 'web-console' gem 'pg' end gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] ruby "2.2.4" Lemme know if there is anything else you need to solve this issue that I am having. Thanks :D |
Ruby on Rails - Users in Groups Posted: 06 Jan 2017 11:08 PM PST I'm trying to implement a Group system where a User can create a Group and other Users can join the Group. class User < ApplicationRecord has_many :groups end class Group < ApplicationRecord belongs_to :owner, :class_name => "User" has_many :members, :class_name => "User" end When checking the owner, I can successfully use: <% if current_user == @group.owner %> But I'm unable to check the members of the group with: <%= @group.members.count %> As I run into an error: SQLite3::SQLException: no such column: users.group_id: SELECT COUNT(*) FROM "users" WHERE "users"."group_id" = ? I think it has something to do with how my Users are setup, but can't figure it out. Also, once I'm able to have a list containing all the Users that have 'joined' the Group, how do I add/remove Users from that? Thanks. |
Paperclip loading images from assets/images directory Posted: 06 Jan 2017 10:08 PM PST how can I call out image using paperclip gem if the image is stored in asset/images/Garden3.jpeg ? I added the record myself using rails console and the following is the value in the DB : #<Product id: 1, product_code: "FB_60", product_description: "Fruits: Apple,Orange,Banana Flowers: Zebra, Chrysa...", price: #<BigDecimal:7f9ec73ec430,'0.6E2',9(18)>, product_image_file_name: "Garden3.jpeg", product_image_content_type: "jpeg", product_image_file_size: nil, product_image_updated_at: nil, category_id: 1> I have an image in the directory asset/images/Garden3.jpeg. Product model will load the images and display the image, price & details . In my Product model i have : class Product < ActiveRecord::Base belongs_to :category has_attached_file :product_image, styles: { small: "64x64", med: "100x100", large: "200x200" }, :url => "/system/products/product_images/000/000/:id/:style/:basename.:extension", :path => ":rails_root/app/assets/images/:basename:extension" end I've also permitted the param name :product_image in the controller. However, when i run the app, there isn't any image shown except the image icon: May i know how can i deal with this problem ? Thanks and appreciate it if I can get some explaination on it to improve. |
Why is jquery sending GET requests with no requested format? Posted: 06 Jan 2017 10:18 PM PST I have this code: $.ajax({ type: type, url: url, contentType: 'application/json', dataType: 'json', accepts: {"json": "application/json"}, success: success, error: errorFunc, async: async }); In development it works as expected. Here's an example log line from my server. method=GET path=/devices format=json controller=DevicesController action=index status=401 duration=0.70 view=0.00 db=0.00 In production on heroku, for some reason the format is blank method=GET path=/devices **format=undefined** controller=DevicesController action=index status=302 duration=1.03 view=0.00 db=0.00 location=https://freedom.to/sign-in (and because of this, my rails app thinks it should send back 302 instead of a 401) What could be causing this discrepancy? |
If I schedule a worker to run every day on Heroku, how can I be sure it doesn't run twice or get skipped? Posted: 07 Jan 2017 01:13 AM PST I'm a bit confused as to how Clockwork, Sidekiq, and Redis all fit together on Heroku given that Heroku restarts dynos at least once a day. Say I have a worker that runs once a day, so it's configured in config/clock.rb as: module Clockwork every(1.day, 'Resend confirmation') { ResendConfirmationWorker.perform_async } end In this worker, I get all the users who have created an account but haven't confirmed it within two days, and resend a confirmation email to each of them. class ResendConfirmationWorker include Sidekiq::Worker sidekiq_options queue: :resend_confirmation, retry: false def perform d = Time.zone.now - 2.days users = User.where.not(confirmation_sent_at: nil) .where(confirmed_at: nil) .where(created_at: d.beginning_of_day..d.end_of_day) users.find_each do |user| user.send_confirmation_instructions end end end Let's say someone signs up on Monday, this job runs on Wednesday, finds them, and sends them a second confirmation email. Then the dyno gets restarted for whatever reason, and the job runs again. They'll get yet another email. Or alternatively, if the restart happens the moment before the job needs to run, then they won't get anything. How does Clockwork have any concept of jobs longer than 24 hours, given that its "lifespan" in a Heroku dyno? Is there a way to simply manage this limitation without having to constantly save this sort of thing to the database? |
Will_paginate, Boosttrap Paginate, and Jquery together: Can I hide section created by the erb loop Posted: 07 Jan 2017 12:23 AM PST I am trying to create my own pagination because I am in sandbox mode for an API. Will_paginate attaches to the index action but won't accept the JSON that I have tried to populate into my sqlite db. So I am making my own pagination using hide, replace, and show <% if (count % 4) == 0 %> </page> <page id="page_section:<%= count %>"> <% end %> My coffescript code: $(document).ready -> $('#example').dataTable() return $('#pagination0').click (event)-> event.preventDefault() $('#page_section:12').hide() This doesn't hide <page id="page_section:12"> ... </page> . Thanks in advance!! |
REST call take much response time than server log response time Posted: 06 Jan 2017 09:20 PM PST I have one rails app Where I have sent a Rest call through postman, or other tools . It is showing much time but my original response time is less . My original response time from server log is 18ms: But my postman response time is 1132ms. Similarly I have a .net app which also got same response time like postman 1123ms. Why this big differences ? between original response time and REST call time |
I just see the post i am so happy to the communication science post of information's.So I have really enjoyed and reading your blogs for these posts.Any way I’ll be replay for your great thinks and I hope you post again soon...
ReplyDeleteEmbedded Training in Chennai
Some truly wonderful work on behalf of the owner of this internet site , perfectly great articles
ReplyDeletepg online
I read this article. I think You put a lot of effort to create this article. I appreciate your work.
ReplyDeletehttps://www.ufa365.info/
Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates. Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates.
ReplyDeleteแทงบอลเต็ง
I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work.
ReplyDeleteแทงบอลสเต็ป
I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.
ReplyDeleteเว็บแทงบอลฝากถอนauto
I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work. เว็บแทงบอลสเต็ปไม่มีขั้นต่ำ
ReplyDeleteConsequently, starting in the amount of electronic marketing strategy, is whenever a company's existing website, which will be to review the present site and its purpose is to improve the potency of the future. There is no evidence that the development and implementation of a method to be significantly different way of electronic marketing. Strategic planning for enterprise development or strategic marketing to comply with the established framework should still be
ReplyDeleteเว็บแทงบอลออโต้
I am always searching online for articles that can help me. There is obviously a lot to know about this. I think you made some good points in Features also. Keep working, great job!
ReplyDeleteUFA365
You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this.
ReplyDeleteทำไมต้องเล่นบาคาร่า
So luck to come across your excellent blog. Your blog brings me a great deal of fun.. Good luck with the site.
ReplyDeleteแทงบาสเว็บไหนดี
Internet search engine optimization experts apply the modern analytics service, which has a positive affect a website. SEO companies are facing great competition in the SEO field. However, they introduce guaranteed SEO services to manage with the competition.
ReplyDeleteบาคาร่าsa-gaming
his is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the excellent work.
ReplyDeleteแทงบาสออนไลน์
his is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the excellent work.
ReplyDeleteคาสิโนออนไลน์ฟรีโบนัส/
Daisy Limousine provides the best black car service in the tri-state area. We can provide limo service or airport service in New Jersey, New York, Rhode Island, Massachusetts, Pennsylvania, and Connecticut. Our on-time ground transportation service will drive you pretty much from A to B anywhere in the North East of America. Give us a call or book a ride online at your convenience
ReplyDeletelucky-god
Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. ประวัตินักกีฬา
ReplyDelete