Trying to validate that an array is not blank in rails [on hold] Posted: 12 Jan 2017 08:19 AM PST I am trying to validate that at least one entry was chosen in a rails dropdown that populates an array. In my model, I have validate :operators_chosen def operators_chosen if (:operators.count <= 1) errors.add(:operators, "must choose at least one") end end But that gives me NoMethodError in SlitterBedsheetsController#create undefined method `count' for :operators:Symbol Rails.root: C:/Users/cmendla/RubymineProjects/slitter_bedsheets Application Trace | Framework Trace | Full Trace app/models/slitter_bedsheet.rb:22:in `operators_chosen' app/controllers/slitter_bedsheets_controller.rb:148:in `block in create' app/controllers/slitter_bedsheets_controller.rb:147:in `create' Request Parameters: {"utf8"=>"✓", "authenticity_token"=>"0TLaXfnuS3r4nUbMSg3Bt+svvwJPvPioCA8s/L++TqbG79l2lZamfl18thD/yzrBao63TRDmgy58TbqA3D42kw==", "slitter_bedsheet"=>{"machine_number"=>"SL-3", "shift"=>"B", "start_time(1i)"=>"2017", "start_time(2i)"=>"1", "start_time(3i)"=>"12", "start_time(4i)"=>"11", "start_time(5i)"=>"12", "date(1i)"=>"2017", "date(2i)"=>"1", "date(3i)"=>"12", "operators"=>["", ""]}, "commit"=>"Create Slitter bedsheet"} I believe that I can validate that at least one operator was chosen by checking that the array count was 1 or greater. Can I modify the code I have here or is there another way to do it? I tried .present? and !....null? but couldn't seem to make them work. |
Rails create list of items based on DB field Posted: 12 Jan 2017 08:17 AM PST In my Rails application I have a Kid model with different allergy fields labeled allergy_one , allergy_two , allergy_three , etc. I want to create a list in my controller called @allergies in order to create a list of items containing Kid 's that have at least one allergy. Some kids have 4 allergies where as some only have 1. I want to be able to use this list in my index to iterate over @allergies in a manner that Kid 's name may be listed multiple times, but each of allergy_one , allergy_two , etc. is listed only once. Here is an example of table I would want displayed: |------------|-------------| | Name | Allergy | |------------|-------------| | Marco | Nuts | | | | | Tim | Dust | | | | | Tim | Cashews | | | | | John | Milk | |------------|-------------| As you see the main model is Kid and it has fields for allergy_one , etc. What I have for allergies so far is: @allergies = Kid.where("allergy_one is NOT NULL") What I need direction for is how I can arrange code in my index.html to display each allergy. All help is appreciated, thanks! |
Add class to bootstrap_form_for collection_select in Rails 5 Posted: 12 Jan 2017 07:59 AM PST I use bootstrap_form_for to create forms and have a collection select, where I want to add a custom class. I tried this, but this does not work: <%= f.collection_select :location, Location.all, :id, :name, label: 'Location', :include_blank => ("Select..."), hide_label: true, :class => 'location' %> Any ideas? |
Rails, Mongoid, using environment variable for database config throws NoMethodError Posted: 12 Jan 2017 08:00 AM PST I'm trying to deploy my rails application, which uses mongoid, to my remote production server. In my mongoid.yml I have added this: hosts: - <%= ENV['MONGOSERVER_PORT_27017_TCP_ADDR'] %>:27017 When I launch my capistrano, it throws me this error: SSHKit::Command::Failed: rake exit status: 1 rake stdout: rake aborted! NoMethodError: undefined method `split' for :"27017":Symbol Does that adding underscores makes this error happen? |
FactoryGirl can't access my models Posted: 12 Jan 2017 07:56 AM PST Problem When I try to run bundle exec rspec , I always get this error: Failure/Error: before { @user = FactoryGirl.build(:user) } NameError: uninitialized constant User Why can't FactoryGirl see my model? Here are some of my files, for reference: Files My factory: # spec/factories/users.rb FactoryGirl.define do factory :user, class: User do email { FFaker::Internet.email } password "12345678" password_confirmation "12345678" end end My model: class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :jogs end My spec: require 'spec_helper' describe 'User' do before { @user = FactoryGirl.build(:user) } subject { @user } it { is_expected.to respond_to(:email) } it { is_expected.to respond_to(:password) } it { is_expected.to respond_to(:password_confirmation) } it { is_expected.to be_valid } end My spec_helper (without all the comments): require 'factory_girl_rails' FactoryGirl.find_definitions RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.shared_context_metadata_behavior = :apply_to_host_groups My rails_helper (without comments): ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) abort("The Rails environment is running in production mode!") if Rails.env.production? require 'spec_helper' require 'rspec/rails' ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| config.fixture_path = "#{::Rails.root}/spec/fixtures" config.use_transactional_fixtures = true config.infer_spec_type_from_file_location! config.filter_rails_from_backtrace! end |
How to get current_user in Rails using devise_token_auth? Posted: 12 Jan 2017 08:12 AM PST I use devise_token_auth with devise for auth and registration. Everything goes well: I can sign in, sign out using api and web interface. But I can't get current_user devise variable (nil). <% if current_user %> <%= link_to "Edit profile", edit_user_registration_path(current_user.id) %> | <%= link_to('Logout', destroy_user_session_path, :method => :delete) %> <% else %> <%= link_to "Register", new_user_registration_path %> | <%= link_to('Login', new_user_session_path) %> <% end %> application_controller.rb class ApplicationController < ActionController::Base include DeviseTokenAuth::Concerns::SetUserByToken protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' } end I need this variable as a global for using, for example, in application.html.erb |
Shopify billing API "undefined method `path' for nil:NilClass" for recurring payment Posted: 12 Jan 2017 07:25 AM PST token = $redis.get("#{params['shop_name']}") ShopifyAPI::Session.setup({:api_key => ENV['SHOPIFY_API_KEY'],:secret => ENV['SHOPIFY_SHARED_SECRET']}) session = ShopifyAPI::Session.new(params["shop_name"], token) ShopifyAPI::Base.activate_session(session) recurring_application_charge = ShopifyAPI::RecurringApplicationCharge.new recurring_application_charge.attributes = { "name" => "Tenant and App charges", "price" => price + 10, "return_url" => "https://admin.#{ENV['SHOPIFY_REDIRECT_HOST']}/shopify/finalize_payment?shop_name=#{params['shop_name']}", # "return_url" => "http://admin.#{ENV['SHOPIFY_REDIRECT_HOST']}/shopify/finalize_payment?shop_name=#{params['shop_name']}", "trial_days" => 30, "terms" => "10 out of 2"} recurring_application_charge.test = true if ENV['SHOPIFY_BILLING_IN_TEST']=="true" if recurring_application_charge.save redirect_to recurring_application_charge.confirmation_url and return end On saving "recurring_application_charge.save" it gives undefined method `path' for nil:NilClass error |
Rails SystemStackError: stack level too deep Posted: 12 Jan 2017 07:06 AM PST i'am trying to do unit tests with rspec in rails. However, i got in my console the following error when i try to save an object to my test db. Here's the output : test = my_object.new(id: 3000, name: "nameTest", last_name: "testLast", company: "testCompany", phone: "testPhone", created_at: DateTime.now, email: "test@test.fr", message: "MY_TEST", status: SpecialSearchesConstants::NEW) 2.2.2 :002 > test.valid? => true 2.2.2 :003 > test.save (0.2ms) BEGIN (0.3ms) ROLLBACK SystemStackError: stack level too deep from /home/ubuntu/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:455:in block in make_lambda' from /home/ubuntu/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:192:in call' from /home/ubuntu/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:192:in `block in simple' (...) After asking google, it seems that this error happend with recurcivity error. However, i have no recursivity in my code. So, is there a way to know exactly where is the problem, or is there is others problems that can cause a "stack level too deep"? I'am brend new in rails, so any clue is welcomed :D Best. |
Can't verify CSRF token authenticity on rails for cross platform request Posted: 12 Jan 2017 07:21 AM PST I am trying to perform cross-platform request in rails. My html code is :- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link type="text/css" rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css"> <link type="text/css" rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css"> <link type="text/css" rel="stylesheet" href="css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <div class="container"> <form class="new_batches" id="new_batch" accept-charset="UTF-8" > <div class="well"> <div class="form-group row"> <label class="control-label col-md-2" for="name">Name </label> <div class="col-md-4"> <input class="form-control" id="name" placeholder="Enter Batch Name" type="text" > </div> </div> <div class="form-group row"> <label class="control-label col-md-2">Course ID</label> <div class="col-md-4"> <input class="form-control" id="course_id" placeholder="Enter Your Course ID" type="text" > </div> </div> <div class="form-group row"> <label class="control-label col-md-2">Start Date</label> <div class="col-md-4"> <input class=" form-control" id="start_date" placeholder="Enter Start Date" type="text" > </div> </div> <div class="form-group row"> <label class="control-label col-md-2"> End Date</label> <div class="col-md-4"> <input class="datepicker form-control" id="end_date" placeholder=" Enter End date" type="text" > </div> </div> <div class="form-group row"> <label class="control-label col-md-2">Status</label> <div class="col-md-2"> <input name="batch[status]" type="hidden" value="0"><input type="checkbox" value="1" checked="checked" id="batch_status"> Checked </div> </div> <div style="margin-left: 110px;"> <button type="submit" id="submit-button" class="btn btn-primary ">Submit</button> </div> </div> </form> </div> <script src="bower_components/jquery/dist/jquery.min.js"></script> <script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script> </body> </html> <script> $(document).ready(function(){ $.ajaxSetup({ headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') } }); }) $(document).ready(function () { $('#submit-button').click(function() { $.ajax({ type: "POST", url: "http://localhost:3000/batches", beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, xhrFields: { withCredentials: true }, data: { batch: { name: $("#name").val(), course_id: $("#course_id").val(), start_date: $("#start_date").val(), end_date: $("
|
No comments:
Post a Comment