Rspec Capybara on simple form Posted: 09 Oct 2016 07:33 AM PDT I am starting to test my app and I am stuck on the user register form... h2 Sign up = simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| = f.error_notification .form-inputs = f.input :first_name, required: true, autofocus: true = f.input :last_name, required: true = f.input :nickname, required: true = f.input :email, required: true = f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) = f.input :password_confirmation, required: true .form-actions =f.button :submit , class:'btn btn-primary' I am following an exemple like this one: describe "Signing up " do it "allows a user to sign up for the site and create object in the database" do expect(User.count).to eq(0) visit "/en/users/sign_up" expect(page).to have_content("Sign up") fill_in "First Name", with: "John" fill_in "Last Name", with: "Doe" fill_in "Nickname", with: "JD" fill_in "Email", with: "john@email.com" fill_in "Password", with: "password" fill_in "Password (again)", with: "password" click_button "Create User" expect(User.count).to eq(1) # end end I dont know how to test the simple form labels?I tried with adding an id to: = f.input :first_name, required: true, autofocus: true, id: "first_name" and the in the spec: fill_in "first_name", with: "John" It doesn't make the job... What should I do ? |
Rails: Restricting to certain records when joining Posted: 09 Oct 2016 07:39 AM PDT Currently I'm using the following to get get all players, go into their player_stats objects, and sum their goals. Player.joins(:player_stats).group('players.id').order('SUM(player_stats.goals) DESC') How can I restrict it not to use all the player_stats objects, what if I only want to sum the goals of the player_stat objects that have a specific game_id? NOTE: I'm using mySQL. |
How to handle httparty errors rails Posted: 09 Oct 2016 07:00 AM PDT I am using some api with httparty gem I have read this question: How can I handle errors with HTTParty? And there are two most upvoted answers how to handle errors first one using response codes (which does not address connection failures) response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') case response.code when 200 puts "All good!" when 404 puts "O noes not found!" when 500...600 puts "ZOMG ERROR #{response.code}" end And the second - catching errors. begin HTTParty.get('http://google.com') rescue HTTParty::Error # don´t do anything / whatever rescue StandardError # rescue instances of StandardError, # i.e. Timeout::Error, SocketError etc end So what is the best practice do handle errors? Do I need to handle connection failures? Right now I am thinking of combining this two approaches like this: begin response = HTTParty.get(url) case response.code when 200 do something when 404 show error end rescue HTTParty::Error => error puts error.inspect rescue => error puts error.inspect end end Is it a good approach to handle both connection error and response codes? Or I am being to overcautious? |
NoMethodError in HealthReport#new Posted: 09 Oct 2016 07:25 AM PDT I keep get this error when I want to render my form The error is pointing the <%= form_for(@hreport) do |f| %>, I'm not sure where when wrong or i missed something, anyone help is appreciate! <div class="col-md-6 col-md-offset-3"> <%= form_for(@hreports) do |f| %> <%= f.label :"Student ID" %> <%= f.text_field :studentid, class: 'form-control' %> This is my health_report_controller.rb class HealthReportController < ApplicationController def index @hreports = Healthreport.where(:user_id => current_user.id) end def new @hreports = Healthreport.new end def create @hreports = current_user.healthreports.build(hreport_params) if @hreports.save flash[:success] = "Report Submitted!" else end end def show @hreports = Healthreport.find(params[:id]) end private def set_hreport @hreport = Healthreport.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def hreport_params params.require(:Healthreport).permit(:date, :studentid, :department, :issue) end end This is my view <% provide(:title, 'New Report') %> <h1>Health and Safety Report</h1> <div class="row"> <div class="col-md-6 col-md-offset-3"> <%= form_for(@hreports) do |f| %> <%= f.label :"Student ID" %> <%= f.text_field :studentid, class: 'form-control' %> <%= f.label :"Department of applicant" %> <%= f.text_field :department, class: 'form-control' %> <%= f.label :"Description of Issues" %> <%= f.text_area :issue, placeholder: "Write your report here...", class: 'form-control' %> <%= f.submit "Submit", class: "btn btn-primary" %> <% end %> This is my healthreport.rb inside model folder class Healthreport < ApplicationRecord belongs_to :user end This is my healthreport.rb inside db folder class CreateHealthreports < ActiveRecord::Migration[5.0] def change create_table :healthreports do |t| t.datetime :date t.string :studentid t.string :department t.string :issue t.timestamps end end end It's migration db file class AddUserToHealthreport < ActiveRecord::Migration[5.0] def change add_reference :healthreports, :user, foreign_key: true end end |
Puzzled with constraints routes in rails Posted: 09 Oct 2016 07:44 AM PDT I am learning rails .And here are some questions I can't understand. class NamespaceConstraint def self.matches?(request) name = request.fullpath.split('/').second.downcase if name[0] == '~' then name = name[1..-1] end ns = Namespace.where(name_lower: request.fullpath.split('/').second.downcase).first not ns.nil? end end Rails.application.routes.draw do constraints(NamespaceConstraint) do get ':namespace' => 'namespaces#show' end end - What does these codes mean?
- In
self.matches? . ? means what? - This
request var wasn't defined,is rails creates it? not ns.nil? This means what? I am a complete beginner to ruby. Thanks for helping me solving this. |
Rails `load': cannot load such file (Rails) when trying to create a new project Posted: 09 Oct 2016 05:05 AM PDT When trying to create a new project in rails I get the following error: MacBook-Air-van-Reinier:Dev reinierverbeek$ rails new project /Users/reinierverbeek/.rvm/gems/ruby-2.3.0/bin/rails:23:in `load': cannot load such file -- /Users/reinierverbeek/.rvm/gems/ruby-2.3.0/gems/rails-5.0.0.1/bin/rails (LoadError) from /Users/reinierverbeek/.rvm/gems/ruby-2.3.0/bin/rails:23:in `<main>' from /Users/reinierverbeek/.rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in `eval' from /Users/reinierverbeek/.rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in `<main>' I have been using Rails for a while and have created many projects in rails before without a problem. I have tried several things. gem install rails This did not work, then I tried gem uninstall rails + gem install rails then I tried gem update then I tried bundle install rails s and rails -v do work after I run bundle install in an old project folder. But outside such a folder rails -v and rails new myProject , return above error. gem list shows that the rails gem is installed: rails (5.0.0.1, 5.0.0, 4.2.6) I recently installed jruby + rails (seperate installation was required for Jruby), but I am not sure if this is related to the issue. Any ideas what my issue could be? |
Failure/Error: specify { expect(response).to redirect_to(root_url) } Posted: 09 Oct 2016 07:38 AM PDT I can not understand, why not pass the tests, it performs the first redirect and not the second, as described in the controller code itself works correctly, redirections occur exactly as described. Rspec 3.5.1 Rails 5 Ruby 2.3.1 describe "as wrong user" do let(:user) { FactoryGirl.create(:user) } let(:wrong_user) { FactoryGirl.create(:user, email: "wrong@example.com") } before { log_in user, no_capybara: true } describe "submitting a GET request to the Users#edit action" do before { get edit_user_path(wrong_user) } specify { expect(response.body).not_to match(full_title('Edit user')) } specify { expect(response).to redirect_to(root_url) } end describe "submitting a PATCH request to the User#update action" do before { patch user_path(wrong_user) } specify { expect(response).to redirect_to(root_url) } end end end The test fails with the following error: 1) AuthenticationPages autorization as wrong user submitting a GET request to the Users#edit action should redirect to "http://www.example.com/" Failure/Error: specify { expect(response).to redirect_to(root_url) } Expected response to be a redirect to <http://www.example.com/> but was a redirect to <http://www.example.com/login>. Expected "http://www.example.com/" to be === "http://www.example.com/login". 2) AuthenticationPages autorization as wrong user submitting a PATCH request to the User#update action should redirect to "http://www.example.com/" Failure/Error: specify { expect(response).to redirect_to(root_url) } Expected response to be a redirect to <http://www.example.com/> but was a redirect to <http://www.example.com/login>. Expected "http://www.example.com/" to be === "http://www.example.com/login". I cannot fathom why it's redirecting to the signin url when it should redirect to the root url - the user is signed in in the spec. Here is the UserController: class UsersController < ApplicationController before_action :logged_in_user, only: [:edit, :update] before_action :correct_user, only: [:edit, :update] def show @user = User.find(params[:id]) end def new @user = User.new end def create @user = User.new(user_params) if @user.save log_in @user flash[:success] = "Welcome to the Sample App!" redirect_to @user else render 'new' end end def edit end def update if @user.update_attributes(user_params) flash[:success] = "Profile updated" redirect_to @user else render 'edit' end end private def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation) end # Before filters def logged_in_user unless logged_in? flash[:danger] = "Please log in." redirect_to login_url end end def correct_user @user = User.find(params[:id]) redirect_to(root_url) unless current_user?(@user) end end Here are the relevant bits of my sessions_helper.rb file: module SessionsHelper # Logs in the given user. def log_in(user) session[:user_id] = user.id end # Returns the current logged-in user (if any). def current_user remember_token = User.encrypt(cookies[:remember_token]) @current_user ||= User.find_by(id: session[:user_id]) end def current_user?(user) user == current_user end # Returns true if the user is logged in, false otherwise. def logged_in? !current_user.nil? end def log_out session.delete(:user_id) @current_user = nil end end User class: class User < ApplicationRecord has_secure_password before_save { self.email = email.downcase } before_create :create_remember_token validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+(\.[a-z]+)*\.[a-z]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },uniqueness: { case_sensitive: false } validates :password, length: { minimum: 6 } def User.new_remember_token SecureRandom.urlsafe_base64 end def User.encrypt(token) Digest::SHA1.hexdigest(token.to_s) end private def create_remember_token self.remember_token = User.encrypt(User.new_remember_token) end end |
Uncaught TypeError: this.template is not a function Backbonejs Posted: 09 Oct 2016 04:22 AM PDT I am working in Rails with BackboneJS in handlebar templates. I am getting a weird error here.. this is my header view class App.Views.Header extends Backbone.View className: "navbar-inner" template: HandlebarsTemplates['app/templates/header'] render: -> @$el.html(@template()) @ main application file is this #= require_self #= require_tree ./templates #= require_tree ./views #= require_tree ./routers window.App = Routers: {} Views: {} Collections: {} Models: {} initialize: -> new App.Routers.MainRouter() Backbone.history.start() and my main router file is this class App.Routers.MainRouter extends Backbone.Router routes: "": "index" initialize: -> @headerView = new App.Views.Header() index: -> $("#header").html(@headerView.render().el) when I hit localhost:3000 .. I got this error upfront. Uncaught TypeError: this.template is not a function .. Am totally stuck in that any help will be appreciated Thanks |
Can't run 'bundle exec rspec spec/' or 'heroku run console' (Mhartl tutorial chapter 6/7) Posted: 09 Oct 2016 07:20 AM PDT Mhartl Ruby on Rails tutorial, chapter 6. I run bundle exec rspec spec/ And get this error Rack::File headers parameter replaces cache_control after Rack 1.5. /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `require': cannot load such file -- /Users/JonasPreisler/rails_projects/sample_app/spec/config/environment (LoadError) So where should this file '/spec/config/environment' come from? Here's the whole error: Jonass-MacBook-Pro:sample_app JonasPreisler$ bundle exec rspec spec/ No DRb server is running. Running in local process instead ... DEPRECATION WARNING: Sass 3.5 will no longer support Ruby 1.9.3. Please upgrade to Ruby 2.0.0 or greater as soon as possible. SECURITY WARNING: No secret option provided to Rack::Session::Cookie. This poses a security threat. It is strongly recommended that you provide a secret to prevent exploits that may be possible from crafted cookies. This will not be supported in future versions of Rack, and future versions will even invalidate your existing user cookies. Called from: /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/actionpack-3.2.3/lib/action_dispatch/middleware/session/abstract_store.rb:28:in `initialize'. Rack::File headers parameter replaces cache_control after Rack 1.5. /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `require': cannot load such file -- /Users/JonasPreisler/rails_projects/sample_app/spec/config/environment (LoadError) from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `block in require' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:236:in `load_dependency' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `require' from /Users/JonasPreisler/rails_projects/sample_app/spec/support/spec_helper.rb:8:in `block in <top (required)>' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/spork-0.9.0/lib/spork.rb:24:in `prefork' from /Users/JonasPreisler/rails_projects/sample_app/spec/support/spec_helper.rb:3:in `<top (required)>' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `require' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `block in require' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:236:in `load_dependency' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `require' from /Users/JonasPreisler/rails_projects/sample_app/spec/spec_helper.rb:9:in `block in <top (required)>' from /Users/JonasPreisler/rails_projects/sample_app/spec/spec_helper.rb:9:in `each' from /Users/JonasPreisler/rails_projects/sample_app/spec/spec_helper.rb:9:in `<top (required)>' from /Users/JonasPreisler/rails_projects/sample_app/spec/controllers/users_controller_spec.rb:1:in `require' from /Users/JonasPreisler/rails_projects/sample_app/spec/controllers/users_controller_spec.rb:1:in `<top (required)>' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/rspec-core-2.9.0/lib/rspec/core/configuration.rb:746:in `load' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/rspec-core-2.9.0/lib/rspec/core/configuration.rb:746:in `block in load_spec_files' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/rspec-core-2.9.0/lib/rspec/core/configuration.rb:746:in `map' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/rspec-core-2.9.0/lib/rspec/core/configuration.rb:746:in `load_spec_files' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/rspec-core-2.9.0/lib/rspec/core/command_line.rb:22:in `run' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/rspec-core-2.9.0/lib/rspec/core/runner.rb:66:in `rescue in run' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/rspec-core-2.9.0/lib/rspec/core/runner.rb:62:in `run' from /Users/JonasPreisler/.rvm/gems/ruby-1.9.3-p551@rails3tutorial2ndEd/gems/rspec-core-2.9.0/lib/rspec/core/runner.rb:10:in `block in autorun' Jonass-MacBook-Pro:sample_app JonasPreisler$ The only folders and files I have in /spec is: - helpers
- models
- requests
- support
- spec_helper.rb
What I tried so far: - Adding 'gem 'test_unit'' to the gemfile
- ran 'bundle install', 'rake db:migrate' and other commands.
- restarting Terminal and text editor.
- Upgrading 'spec-rails' and 'capybara'
Thank you. |
Can't create data rails, no method error Posted: 09 Oct 2016 03:12 AM PDT I'm implementing a website using Ruby on Rails. I have a trouble which I cannot create a new data and save to my model. The error i got is this which the error pointed to the @vpermits = current_user.vpermits.build(vpermit_params). Anyone have idea on what I have i done wrong? NoMethodError in VisitorPermitsController#create undefined method `vpermits' for #<User:0x9b7b478> def create @vpermits = current_user.vpermits.build(vpermit_params) if @vpermits.save redirect_to @vpermits else This is my visitor_permits_controller.rb class VisitorPermitsController < ApplicationController before_action :set_vpermit, only: [:destroy] def index @vpermits = VisitorPermit.where(:user_id => current_user.id) end def new @vpermits = VisitorPermit.new end def create @vpermits = current_user.vpermits.build(vpermit_params) if @vpermits.save redirect_to @vpermits else render 'new' end end def destroy VisitorPermit.destroy_all(user_id: current_user) respond_to do |format| format.html { redirect_to root_path, notice: 'Permit was successfully canceled.' } format.json { head :no_content } end end def show @vpermits = VisitorPermit.find(params[:id]) end def update @vpermits = VisitorPermit.where(user_id: current_user).take respond_to do |format| if @vpermits.update(vpermit_params) format.html { redirect_to root_path} flash[:success] = "Permit successfully updated" format.json { render :show, status: :ok, location: @user } else format.html { render :edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end end def edit @vpermits = VisitorPermit.find(params[:id]) end private # Use callbacks to share common setup or constraints between actions. def set_vpermit @vpermits = VisitorPermit.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def vpermit_params params.require(:visitor_permit).permit(:vehicle_type, :name, :department, :carplate, :duration, :permitstart, :permitend) end end |
Unable to send mails using Discourse Posted: 09 Oct 2016 03:40 AM PDT I have docker installation of discourse from this article. Discourse is working fine but I am unable to send mails. I have tried this article for troubleshooting with no lucks. my settings are. ## TODO: The mailserver this Discourse instance will use DISCOURSE_SMTP_ADDRESS: smtp.zoho.com # (mandatory) DISCOURSE_SMTP_PORT: 587 # (optional) DISCOURSE_SMTP_USER_NAME: xxxxx@xxxxxx.in # (optional) DISCOURSE_SMTP_PASSWORD: xxxxxxxxx # (optional) ## when I check production logs it shows Unprocessable entry. Started POST "/admin/email/test" for 106.51.227.84 at 2016-10-09 10:36:28 +0000 Processing by Admin::EmailController#test as */* Parameters: {"email_address"=>"geekceeaim@gmail.com"} Sent mail to geekceeaim@gmail.com (1430.7ms) Completed 422 Unprocessable Entity in 1871ms (Views: 0.7ms | ActiveRecord: 1.1ms) Please help me out. Thanks in advance. |
Routing with parameters not working on rails Posted: 09 Oct 2016 02:48 AM PDT I've been trying to figure this one out but I'm becoming desperate because I don't see why this isn't working. Whatever I try, no route is matching my link and I get the following error: Routing Error: uninitialized constant LineItemsController My link looks like this: <%= button_to 'Add to template', line_items_path(template_id: @template, position_id: position) %> So the link being created is: http://localhost:3000/line_items?position_id=2&template_id=1 routes.rb: Rails.application.routes.draw do resources :line_items resources :templates resources :positions line_item_controller.rb class LineItemsController < ApplicationController before_action :set_line_item, only: [:show, :edit, :update, :destroy] # GET /line_items # GET /line_items.json def index @line_items = LineItem.all end # GET /line_items/1 # GET /line_items/1.json def show end # GET /line_items/new def new @line_item = LineItem.new end # GET /line_items/1/edit def edit end # POST /line_items # POST /line_items.json def create position = Position.find(params[:position_id]) template = Template.find(params[:template_id]) @line_item = LineItem.new(position, template) respond_to do |format| if @line_item.save format.html { redirect_to template_url} format.js {@current_item = @line_item} format.json { render action: 'show', status: :created, location: @line_item } else format.html { render action: 'new' } format.json { render json: @line_item.errors, status: :unprocessable_entity } end end end # PATCH/PUT /line_items/1 # PATCH/PUT /line_items/1.json def update respond_to do |format| if @line_item.update(line_item_params) format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @line_item.errors, status: :unprocessable_entity } end end end # DELETE /line_items/1 # DELETE /line_items/1.json def destroy @line_item.destroy respond_to do |format| format.html { redirect_to line_items_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_line_item @line_item = LineItem.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. # def line_item_params # params.require(:line_item).permit(:position_id, :template_id) # end #... end From my understanding, my link should send a POST request that should call the create action of the line_item controller , thereby matching the route POST /line_items(.:format) line_items#create Thanks for the help guys! |
Get records created after a particular time of day Posted: 09 Oct 2016 07:05 AM PDT Say I have an Event model with a date_time field representing the date time the event is held, and I want to see all Events that are held, say, 'after 10pm', or 'before 7am' across multiple dates. How could I do this? My first thought was something like this: scope :after_time ->(time){ where("events.date_time::time between ?::time and '23:59'::time", time) } But this doesn't work because dates are stored in UTC and converted to the app's timezone by ActiveRecord. So let's say I'm searching for Events after 5pm, from my local Adelaide time. The eventual query is this: WHERE (events.date_time::time between '2016-10-09 06:30:00.000000'::time and '23:59'::time) That is, because my timezone is +10:30 (Adelaide time), it's now trying to calculate between 6:30am and midnight, where it really needs to be finding ones created between 6:30am and 1:30pm utc. Now, for this example in particular I could probably hack something together to work out what the 'midnight' time needs to be given the time zone difference. But the between <given time> and <midnight in Adelaide> calculation isn't going to work if that period spans midnight utc. So that solution is bust. UPDATE: I think I've managed to get the result I want by trial and error, but I'm not sure I understand exactly what's going on. scope :after_time, ->(time) { time = time.strftime('%H:%M:%S') where_clause = <<-SQL (events.date_time at time zone 'UTC' at time zone 'ACDT')::time between ? and '23:59:59' SQL joins(:performances).where(where_clause, time) } It's basically turning everything into the one time zone so the query for each row ends up looking something like WHERE '20:30:00' between '17:00:00' and '23:59:59' , so I'm not having to worry about times spanning over midnight. Even still, I feel like there's probably a proper way to do this, so I'm open to suggestions. |
Rails 4 Rspec and Factory Girl URI::InvalidURIError multitenancy Posted: 09 Oct 2016 01:48 AM PDT Im following a tutorial on Rails 4 and multi-tenancy, but am getting an error when trying to test if a user can sign in as an owner and redirect to a created subdomain. this is the test error: Failures: 1) User sign in signs in as an account owner successfully Failure/Error: visit root_url URI::InvalidURIError: bad URI(is not URI?): http://#{account.subdomain}.example.com # /Users/developer/.rvm/gems/ruby-2.3.1/gems/capybara-2.10.1/lib/capybara/rack_test/browser.rb:71:in `reset_host!' # /Users/developer/.rvm/gems/ruby-2.3.1/gems/capybara-2.10.1/lib/capybara/rack_test/browser.rb:21:in `visit' # /Users/developer/.rvm/gems/ruby-2.3.1/gems/capybara-2.10.1/lib/capybara/rack_test/driver.rb:43:in `visit' # /Users/developer/.rvm/gems/ruby-2.3.1/gems/capybara-2.10.1/lib/capybara/session.rb:240:in `visit' # /Users/developer/.rvm/gems/ruby-2.3.1/gems/capybara-2.10.1/lib/capybara/dsl.rb:52:in `block (2 levels) in <module:DSL>' # ./spec/features/users/sign_in_spec.rb:9:in `block (3 levels) in <top (required)>' Finished in 0.56981 seconds (files took 1.26 seconds to load) 11 examples, 1 failure, 6 pending this is the test: require "rails_helper" feature "User sign in" do extend SubdomainHelpers let!(:account) { FactoryGirl.create(:account) } let(:sign_in_url) {"http://#{account.subdomain}.example.com/sign_in"} let(:root_url) {"http://#{account.subdomain}.example.com/"} within_account_subdomain do scenario "signs in as an account owner successfully" do visit root_url expect(page.current_url).to eq(sign_in_url) fill_in "Email", :with => account.owner.email fill_in "Password", :with => "password" click_button "Sign in" expect(page).to have_content("You are now signed in.") expect(page.current_url).to eq(root_url) end end end here are the factories: Account: FactoryGirl.define do factory :account, :class => Subscribe::Account do sequence(:name) { |n| "Test Account ##{n}" } sequence(:subdomain) { |n| "test#{n}" } association :owner, :factory => :user end end User: FactoryGirl.define do factory :user, :class => Subscribe::User do sequence(:email) { |n| "test#{n}@example.com" } password "password" password_confirmation "password" end end I am really not familiar with BDD, please let me know if you need me to post anything further |
"heroku run rake db:migrate" command returns ETIMEDOUT error message Posted: 09 Oct 2016 12:22 AM PDT Any ideas why I might be getting the below error message? $ git push heroku master Everything up-to-date $ heroku run rake db:migrate Running rake db:migrate on ⬢ agile-retreat-87004... ! ▸ ETIMEDOUT: connect ETIMEDOUT 50.19.103.36:5000 |
Facing error while running rails server command "rails server" on win 8 Posted: 08 Oct 2016 11:46 PM PDT error was: could not find gem 'uglifier ( = 1.3.0) ruby' in the gems available on this machine. I googled and found on stackoverflow to install uglifier gem manually using "gem install uglifier" command, Now, this is also showing ssl error: "could not find a valid gem 'uglifier' <>=0>,here is why,unable t0 download data form https://railsgem.org/- SSL_connect returned -1 error 0 state-SSL3 read server certification B: certification validation failed." Ruby version: 2.2.4p230 Rails Version: 4.2.5.1 Please help. |
Rails - Business opening hours schema Posted: 09 Oct 2016 12:09 AM PDT I have a Venue model that has_many and accept_nested_attributes_for working_hours. The Working Hour model: create_table "working_hours", force: :cascade do |t| t.integer "day" t.time "open_time" t.time "close_time" t.integer "venue_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["merchant_id"], name: "index_working_hours_on_merchant_id", using: :btree end That way I can add more than one working_hour block per day, as: Sunday 10am - 13am Sunday 17pm - 20pm But, how can I handle with venues that close after midnight (ex: 20pm - 1am) ? |
Ruby on rails get id from instance variable Posted: 09 Oct 2016 12:03 AM PDT I have an instance variable @user so in HTML <%=link_to @user %> gives me the result: {"id"=>2, "restaurant"=>"sea food", "password"=>"123", "name"=>"a", "email"=>"a", "telephone"=>"123", "created_at"=>"2016-10-09T04:00:24.010Z", "updated_at"=>"2016-10-09T04:00:24.010Z"} I want to get the value of id, but when I write:<%=link_to @user[:id] %> it returns me the result :/restaurant/home , which is the route of my home function inside my restaurant controller and I can't understand why. This is my controller: class RestaurantController < ApplicationController def home @user = session['loginedUser'] end def login end def checkLogin @user = User.find_by_restaurant(params[:user][:restaurant]) if @user != nil && @user[:password] == params[:user][:password] session['loginedUser'] = @user redirect_to :controller=>'restaurant',:action=>'home' else session['loginedUser'] = nil # redirect_to :controller=>'restaurant',:action=>'login' end end def logout session['loginedUser'] = nil redirect_to :controller=>'restaurant',:action=>'home' end end Can anybody help? Thanks a lot. |
How to count 1 to 9 on a single line in ruby Posted: 09 Oct 2016 02:13 AM PDT I'm struggling to figure out how to loop numbers in a single line on ruby. x = 0 while x <= 9 puts x x +=1 end This would give you 0 1 2 3 4 5 6 7 8 9 Each on different lines. But what I want is to get this on a single line so like 01234567891011121314151617181920 Also not limited to just 0-9 more like 0 to infinity on a single line. The purpose is to make an triangle of any size that follows this pattern. 1 12 123 1234 12345 123456 Each of these would be on a different line. The formatting here won't let me put in on different lines. Would really like to solve this. It is hurting my head. |
Deploying Rails Application Under Apache , In VPS Posted: 09 Oct 2016 02:21 AM PDT I Want To Deploy Rails Application On My Vps , Which Already Uses Apache As Web Server. How Can I Accomplish This ? |
Incomplete response received from application - Passenger & NGINX Posted: 08 Oct 2016 10:11 PM PDT I have successfully installed rails with Passenger+Nginx but am experiencing an Incomplete response error via the web browser: http://tenklakes.northcentralus.cloudapp.azure.com/ I have tried rake secrets to generate a new secret_key_base for production in my secrets.yml file with no luck. Secrets.yml : development: secret_key_base:c70c590cfe799087c47528016ab49a1a8e57fe2eb851639e27e2ea66f92f241a0400b3d4247e3d61a6c82818dd3988825deeb66e783ba90cfccfbc0c500d6dbd test: secret_key_base: 08b1ebf5defee2eb1ad196e9780ae118f256c9f40f40f76674451dac4dfb1c42b75f04d22ee264644711de4e547ac8f58031e88f09c5c7223834b99230fb205c # Do not keep production secrets in the repository, # instead read values from the environment. production: secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> when I run curl http:0.0.0.0:3000 I receive the following from Passenger: Started GET "/" for 127.0.0.1 at 2016-10-09 04:52:43 +0000 Processing by Rails::WelcomeController#index as */* Parameters: {"internal"=>true} Rendering /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/templates/rails/welcome/index.html.erb Rendered /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/templates/rails/welcome/index.html.erb (2.5ms) Completed 200 OK in 10ms (Views: 6.2ms | ActiveRecord: 0.0ms) NGINX error.log : [ 2016-10-09 04:49:44.8271 45647/7fe3b30d4700 age/Cor/Con/InternalUtils.cpp:112 ]: [Client 1-3] Sending 502 response: application did not send a complete response App 45674 stderr: [ 2016-10-09 04:49:56.0108 45754/0x0000000092d678(Worker 1) utils.rb:87 ]: *** Exception RuntimeError in Rack application object (Missing secret_key_base for 'production' environment, set this value in config/secrets.yml ) (process 45754, thread 0x0000000092d678(Worker 1)): App 45674 stderr: from /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/application.rb:513:in validate_secret_key_config!' App 45674 stderr: from /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/application.rb:246:in env_config' App 45674 stderr: from /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:693:in build_request' App 45674 stderr: from /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/application.rb:521:in build_request' App 45674 stderr: from /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:521:in call' App 45674 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:97:in process_request' App 45674 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:152:in accept_and_process_next_request' App 45674 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:113:in main_loop' App 45674 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler.rb:416:in block (3 levels) in start_threads' App 45674 stderr: from /usr/lib/ruby/vendor_ruby/phusion_passenger/utils.rb:113:in block in create_thread_and_abort_on_exception' I am out of ideas to get this working - is there anything else I should be checking? |
Nginx + Rails, Default url not working Posted: 08 Oct 2016 09:15 PM PDT I supposedly have my default url set as example.com/asd ---> my root_path and is serving everything correctly. However, everytime I click a '<%= link_to 'something', something_path %>' I'm directed to example.com ---> without the /asd. Is this a problem with my nginx configurations or rails configuration? And what should I do to solve it? |
Regarding using anyenv, rbenv, ndenv in production environment, CentOS7.* Posted: 09 Oct 2016 04:47 AM PDT Currently I'm creating the web service with CentOS7.* and ruby on rails 5.* and ruby 2.* and node.js 6.*. In the development environments, I'm using anyenv and rbenv and ndenv. Since the installing of ruby and node.js and the exchanging of their versions are easy. Now I'd like to adopt these tools(anyenv, rbenv, ndenv) in the production environment, too. However, I have never used them in the production. Also, CentOS7.* does not support them officially. Generally, I think using the packages that are supported by CentOS officially is safer. I'm worried about the troubles which were occurred by using them in the production. Could you tell me if there is anyone who have experienced to use the tools(anyenv, rbenv, ndenv) in the production environment. Did you have any troubles or etc... |
link_to html page directly in Rails Posted: 08 Oct 2016 09:02 PM PDT I want to link to a html page directly using link_to method. For example, define a controller named UsersController, and there is a html page, named welcome.html.erb, without welcome action definition in UsersController, if so, how can I implement the linking to this page directly with link_to? |
Timeout of a long request in a Rails application -- can I set it up? Posted: 08 Oct 2016 08:04 PM PDT When a client sends a syncronoous request to a Rails application and if an operations takes a long time, timeout occurs. What determines the time interval after which timeout occurs? Can I set it up? Or does it have to do with a Rails application or maybe http protocol instead? |
Routing error after trying to make a post Posted: 08 Oct 2016 08:00 PM PDT I'm getting a confusing routing error after trying to submit a post. the error is No route matches [POST] "/blog" despite it being in routes.rb. Here is my route file: Rails.application.routes.draw do get 'welcome/index' get '/blog', to: 'posts#post', as: :post get '/geobot', to: 'welcome#geobot', as: :geobot get "/blog/show/:id", to: 'posts#show' get '/blog/new', to: 'posts#new', as: :new root 'welcome#index' end and post controller: class PostsController < ApplicationController def post end def new end def create @post = Post.new(post_params) @post.save redirect_to @post end def show @post = Post.find(params[:id]) end private def post_params params.require(:post).permit(:title, :body) end end |
rails dynamic where sql query Posted: 08 Oct 2016 11:00 PM PDT I have an object with a bunch of attributes that represent searchable model attributes, and I would like to dynamically create an sql query using only the attributes that are set. I created the method below, but I believe it is susceptible to sql injection attacks. I did some research and read over the rails active record query interface guide, but it seems like the where condition always needs a statically defined string as the first parameter. I also tried to find a way to sanitize the sql string produced by my method, but it doesn't seem like there is a good way to do that either. How can I do this better? Should I use a where condition or just somehow sanitize this sql string? Thanks. def query_string to_return = "" self.instance_values.symbolize_keys.each do |attr_name, attr_value| if defined?(attr_value) and !attr_value.blank? to_return << "#{attr_name} LIKE '%#{attr_value}%' and " end end to_return.chomp(" and ") end |
RDoc syntax highlighting for Ruby in Sublime Text 2 [on hold] Posted: 08 Oct 2016 06:49 PM PDT Question: What would the syntax definition be in .YAML-tmLanguage format for a syntax that recognizes both RDoc and Ruby simultaneously? References: |
Ruby Postgresql PGconn.connect takes up to 60 seconds to initialize Posted: 08 Oct 2016 05:40 PM PDT Trying to do some rails dev under windows and I'm finding that the initial connection to postgres is taking up to 60 seconds. I dug into the activerecord postgresql adapter and added some profiling in the connect method. require 'ruby-prof' GC::Profiler.enable GC.start RubyProf.start p @connection_parameters @connection = PGconn.connect(@connection_parameters) result = RubyProf.stop printer = RubyProf::FlatPrinter.new(result) printer.print(STDOUT) puts GC::Profiler.report STDOUT.flush This gives the following output: Measure Mode: wall_time Thread ID: 7790520 Fiber ID: 7613460 Total: 52.288858 Sort by: self_time %self total self wait child calls name 99.94 52.258 52.257 0.000 0.001 1 PG::Connection#initialize 0.06 0.031 0.031 0.000 0.000 1 Kernel#p 0.00 0.001 0.001 0.000 0.000 1 Array#pop 0.00 0.000 0.000 0.000 0.000 1 String#sub 0.00 0.000 0.000 0.000 0.000 1 Array#each 0.00 0.000 0.000 0.000 0.000 3 Symbol#to_s 0.00 0.000 0.000 0.000 0.000 1 Hash#each 0.00 0.000 0.000 0.000 0.000 1 Enumerable#map 0.00 0.000 0.000 0.000 0.000 1 Hash#merge! 0.00 0.000 0.000 0.000 0.000 1 Array#zip 0.00 0.000 0.000 0.000 0.000 3 String#to_s 0.00 0.000 0.000 0.000 0.000 36 Symbol#to_sym 0.00 0.000 0.000 0.000 0.000 3 <Class::PG::Connection>#quote_connstr 0.00 0.000 0.000 0.000 0.000 1 Enumerable#find 0.00 0.000 0.000 0.000 0.000 1 Module#instance_methods 0.00 0.000 0.000 0.000 0.000 3 String#gsub 0.00 0.000 0.000 0.000 0.000 1 Kernel#is_a? 0.00 0.000 0.000 0.000 0.000 1 Array#last 0.00 0.001 0.000 0.000 0.001 1 <Class::PG::Connection>#parse_connect_args 0.00 0.000 0.000 0.000 0.000 1 Array#join 0.00 52.258 0.000 0.000 52.258 1 <Class::PG::Connection>#connect 0.00 0.000 0.000 0.000 0.000 2 String#inspect 0.00 0.000 0.000 0.000 0.000 2 Symbol#inspect 0.00 0.000 0.000 0.000 0.000 1 Hash#inspect 0.00 0.000 0.000 0.000 0.000 1 String#% 0.00 52.289 0.000 0.000 52.289 1 ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#connect * indicates recursively called methods GC 36 invokes. Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms) 1 12.609 12175480 22293120 557328 125.00000000000000000000 If I strip away everything else and just pass the exact some connection parameters to PGconn.connect without loading rails or any other libraries, I can connect in 2 seconds: $ time PGUSER=username PGPASSWORD=password ruby -rpg -rruby-prof -e "GC::Profiler.enable; GC.start; RubyProf.start; settings = {:host => 'localhost', :dbname => 'dbname_development'}; PGconn.connect(settings); r=RubyProf.stop; RubyProf::FlatPrinter.new(r).print(STDOUT); puts GC::Profiler.report; STDOUT.flush" Measure Mode: wall_time Thread ID: 20316120 Fiber ID: 20135520 Total: 2.675508 Sort by: self_time %self total self wait child calls name 100.00 2.676 2.676 0.000 0.000 1 PG::Connection#initialize 0.00 0.000 0.000 0.000 0.000 1 String#sub 0.00 0.000 0.000 0.000 0.000 3 String#to_s 0.00 0.000 0.000 0.000 0.000 3 <Class::PG::Connection>#quote_connstr 0.00 0.000 0.000 0.000 0.000 3 Symbol#to_s 0.00 0.000 0.000 0.000 0.000 1 Hash#each 0.00 0.000 0.000 0.000 0.000 1 Enumerable#map 0.00 0.000 0.000 0.000 0.000 1 Hash#merge! 0.00 0.000 0.000 0.000 0.000 1 Array#zip 0.00 0.000 0.000 0.000 0.000 3 String#gsub 0.00 0.000 0.000 0.000 0.000 46 Symbol#to_sym 0.00 0.000 0.000 0.000 0.000 1 Array#each 0.00 0.000 0.000 0.000 0.000 1 Enumerable#find 0.00 0.000 0.000 0.000 0.000 1 Module#instance_methods 0.00 0.000 0.000 0.000 0.000 1 Array#pop 0.00 0.000 0.000 0.000 0.000 1 Kernel#is_a? 0.00 0.000 0.000 0.000 0.000 1 Array#last 0.00 0.000 0.000 0.000 0.000 1 <Class::PG::Connection>#parse_connect_args 0.00 0.000 0.000 0.000 0.000 1 Array#join 0.00 2.676 0.000 0.000 2.676 1 <Class::PG::Connection>#connect * indicates recursively called methods GC 14 invokes. Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms) 1 0.562 895840 1338240 33456 15.62500000000000000000 real 0m3.795s user 0m0.015s sys 0m0.046s As I add more an more required libraries, the connection time increases. I think libraries that include native components might make more of an impact, but not 100% on that. It's using more memory, but it's not hitting swap, and the GC time isn't significantly more. Any pointers on which rabbit hole to go down to investigate further? Running versions: $ ruby -v ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32] $ gem list pg --local pg (0.19.0 x64-mingw32) |
ruby on rails active record find depends on params Posted: 08 Oct 2016 08:21 PM PDT Hello Stack Overflowers. I need to know, how to write rails query which depends on GET params. For exapmle i have action localhost/users?text=aaa&city=NY and now i want to write query to search all users where firstname,lastname,username,email is LIKE %text% and user city is NY Of course when there is no city in params there is no included in query in the same way where is no text show all users from city. I want to know your solutions for this case. Greetings |
No comments:
Post a Comment