spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » RUBY ON RAILS » Page 10
Ruby: Using require produces "in `require': cannot load such file "
You have an unwanted dot in unit., replace your require with: require File.expand_path("../../test_helper", __FILE__) # Or maybe require File.expand_path("../test_helper", __FILE__)

Categories : Ruby On Rails

Rails: return only json
Use respond_with instead of respond_to in your controller action. respond_with do |format| respond_to at the top of your controller is designed to work with respond_with in your controller action, whereas respond_to in your controller action ignores the respond_to that you've defined at the top of your controller. Also make sure you are making a remote call, instead of a normall one if you wan

Categories : Ruby On Rails

Customizing devise controller
I think you need to be overriding the registrations controller: devise_for :users, :controllers => {:registrations => "registrations"} Then the controller: controllers/registrations_controller.rb class RegistrationsController < Devise::RegistrationsController def create build_resource(sign_up_params) admin_user = User.find_by_role(User::admin_role) if admin_user.nil?

Categories : Ruby On Rails

How to get all the associated models from ActiveRecord object?
Order.reflect_on_all_associations.map(&:class_name) You can pass a type of relation as a parameter: Order.reflect_on_all_associations(:has_one) Read about ActiveRecord::Reflection::ClassMethods EDIT Just realised, you've asked about object's associated models. So, having what I've already showed, you can simply do something along the following lines: @some_order = Order.first associate

Categories : Ruby On Rails

ActiveRecord saving: differences in Rails 3.2.19 and Rails 4.2.0
This is related with Strong Parameters which are enabled by default in the 4.x version. Taking the example from the documentation: class PeopleController < ActionController::Base # This will raise an ActiveModel::ForbiddenAttributes exception because it's using mass assignment # without an explicit permit step. def create Person.create(params[:person]) end # This will pass with

Categories : Ruby On Rails

Rails: working on temporary instance between requests and then commit changes to database
As HTTP requests are stateless you need some kind of storeage between requests. The session is the easiest way to store data between requests. As for you the session will not be enough because you need it to be accessed by multiple users. I see two ways to achive your goal: 1) Get some fast external data storage like a key-value server (redis, or anything you prefer http://nosql-database.org/)

Categories : Ruby On Rails

Command line gem install error - sqlite3 - Rails New Command
Perhaps this problem has to do with a recent update of XCode. After a XCode update you need to do the following steps: Open Xcode and accept the license agreement Reinstall the Command Line Tools. The second step seems to depend on your OS versions. If xcode-select --install does not work try to start the Install Command Line Developer Tools app in /System/Library/CoreServices. After reinstal

Categories : Ruby On Rails

rails joins with select returns nil as id
You should use only option of to_json method: Foo.select('bars.comment_1, bars.comment_2, foos.rating').joins(:bars).each do |b| p b.to_json(only: [:comment_1, :comment_2, :rating]) end

Categories : Ruby On Rails

Rails + Using Friendly ID for slug generation and creating trouble while accessing from DB
There is a difference between what you see the value of slug in Tutorial.last and what you get in Tutorial.last.slug Tutorial.last fetches the last record from the table which is giving you the slug saved in the database, but Tutorial.last.slug is calling the slug method defined in your model, Tutorial.last is an object and using that object you are calling the slug method def slug title.strip

Categories : Ruby On Rails

Display attributes in loca ltime in ActiveAdmin Admin panel
You can set default time_zone in your active_admin initializer (config/initializers/active_admin.rb) file like this: config.namespace :admin do |admin| admin.time_zone = 'Eastern Time (US & Canada)' end Please refer this link: How to change how ActiveAdmin displays time (every time)

Categories : Ruby On Rails

How to access private class methods in Rails
Both of your approaches are correct, but in the latter you shouldn't use self, cause you already define method in Initialization's eigenclass: class Initialization class << self def send_mail a = user_stats end private def user_stats true end end end Initialization.send_mail # => true Your first approach also works for me: class Initialization def

Categories : Ruby On Rails

Custom field Devise
What you need to do is to customize devise registration, do the following Generate registration code $ rails generate devise:controllers users registrations $ rails generate devise:views users registrations Add to routes.rb devise_for :users, controllers: { registrations: "users/registrations" } I assume you know how to add a nested attribute called organization to your signup form. Anywa

Categories : Ruby On Rails

ActiveRecord transaction not rolling back on failure
Yep. Transaction will fail if an exception is raised. You should use not create, but create! that will do that in case of failure. See here.

Categories : Ruby On Rails

Sync My Timesheets to QuickBooks in Rails App
Create an account on https://developer.intuit.com Create an app and sandbox after logging in. Hook up Rails to talk to the sandbox. See my tutorials to help with these 3 steps. TimeActivity is supported by the quickbooks-ruby gem so check the docs and specs for implementation. You will need to implement the Employee or Vendor entity as that reference is required to sync TimeActivity. When ready

Categories : Ruby On Rails

using 18n and I18n:Alchemy in rails in order to translate a text value according to the locale
Can't see the problem if you're already using i18n localization. Just use the field as a key for i18n (with a prefix if you like) t("prefix_#{credit_debit}") and just define the strings for both your locales. So in your en locale: prefix_credit: credit prefix_debit: debit And in your it locale: prefix_credit: avere prefix_debit: dare

Categories : Ruby On Rails

nginx starting error with rails Phusion Passenger
Kill the service and then start it again. $ ps -A | grep -i passenger | xargs kill -9 Try with sudo if you get errors. Just in case this command is not working do: $ kill -9 $(pgrep Passenger) Usually I get this error when another instance is running.

Categories : Ruby On Rails

Can I start separate port on heroku for EventMachine?
No, it is not possible to open a port on heroku to run an event machine web socket as detailed in your question. The routing layer will only proxy ports 80 and 443 through to your app which will be listening on some arbitrary port provided by heroku when your app starts up. Clients will be unable to connect to the web socket on the port you specified. See here for an example of using web sockets

Categories : Ruby On Rails

How do I send specific emails to subscribers
So there's no better place than the official documentation for starting: http://guides.rubyonrails.org/action_mailer_basics.html If you are looking where you should call the method to send the email, you probably want to do it in the controller, in the method that receives the form POST. Have a look at this example, taken from the guides: class UsersController < ApplicationController # PO

Categories : Ruby On Rails

ActiveRecord has_many association null
I think the problem is that you used session_player, but it should be session_players, use this line instead <% session.session_players.each do |player| %> And in your model, since you are using has_many, you should use pluralized form of model name has_many :session_players

Categories : Ruby On Rails

Rails4 JSON Parameters Parse error while Create
In you params: "company"=> is a hash key "{"description":"Description of the company","name":"Google"}" is a string, hash value [2] pry(main)> JSON.parse "{"description":"Description of the company","name":"Google"}" => {"description"=>"Description of the company", "name"=>"Google"} gives correct output

Categories : Ruby On Rails

WickedPDF different margin settings for first page?
Add a script with the --header-html set to the following: <!DOCTYPE html> <html> <head> <script> function subst() { var vars = {}; var x = document.location.search.substring(1).split('&'); for (var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);} if(vars['page'] == 1) { // If page is 1, do not show t

Categories : Ruby On Rails

Mysql equivalent rails query
You normally don't really query like that directly with Rails. Instead, you'd set up your models and use other associated models to achieve this. If speed is an issue, you can use eager loading. If you absolutely need exactly this join, it's: class Article < ActiveRecord::Base has_many :books scope :with_books, lambda { joins(:books) .select('articles.code, books.name, books.pri

Categories : Ruby On Rails

add custom validation method in Ruby on Rails
You don't need custom validation to do this, you can use regex to validate the format of password. Add this to your model validates :password, format: { with: /^(?=.*[A-Z]).+$/, allow_blank: true } In Rails, you can do this by using format validator, I have added allow_blank: true to make sure when the field is empty it only throws Can't be blank error message and not format validator error mes

Categories : Ruby On Rails

Rails — How do I see old and new model values from an after_save callback?
In after_save, if you use changes method, it returns the hash of all the changes on your object. You can specify which attribute's changes you need. This will be an array. [old-value, new-value] In your Example, it can be self.p.changes["score"]. This returns an array [0, 1], where 0 is old value, 1 is new value

Categories : Ruby On Rails

RSpec and Capybara matchers failing
Figured it out. It is a result of this logged issue. The problem is that the title element will not be found by some web drivers (it is considered invisible). This was fixed in Capybara by adding a visible: switch to have_selector and has_selector. I changed my matcher to this: RSpec::Matchers.define :have_valid_header_and_title do |heading, page_title| match do |page| if (heading) then

Categories : Ruby On Rails

trying to render a partial based on whether it's the home page "/"
According to this answer you can do this: <% if current_page?(root_url) %> <%= render 'layouts/homeHeader' %> <% else %> <%= render 'layouts/header' %> <% end %>

Categories : Ruby On Rails

How to use Rspec any_instance_of if you don't know all the WITH values
I think what you are looking for is the kind_of method user = User.make! expect_any_instance_of(Notifier).to receive(:tell_user).with(user.id, kind_of(Numeric)) Message.create(author: User.make!, recepient: user, message: 'this is a test') You can also use instance_of(Fixnum) if you want to be more specific

Categories : Ruby On Rails

How do I see which params are failing a mass_assignment error?
I don't know about using pry for it. But when you have rails app running, you can make tail -f log/development.log and there will be written which params are not whitelisted

Categories : Ruby On Rails

Why is this scope causing recusion in my rails app?
The problem is that your scope is named name. The name method normally returns the class name. Some Rails code makes use of the name method, such as the parent_name method in the introspection module: def parent_name if defined? @parent_name @parent_name else @parent_name = name =~ /::[^:]+/ ? $`.freeze : nil # This line calls the "name" method end end parent_name can take a

Categories : Ruby On Rails

Setting up routes for url shortener
If you want to be able to have multiple slashes you'll need something like: get '*id', to: 'home#show' If you only want a single subpath (i.e. /23af1) it's probably better to use: get ':id', to: 'home#show' You can find more info in the Rails Guide

Categories : Ruby On Rails

Passing data from Ajax to Rails controller
Within your ajax call you should specify the method (in this case, looks like a GET) and the data required: $.ajax({ type: "GET", url: "/songs_echowrap/" + randomA.a_name, data: randomA.a_name, }).success(function(data) { Do Stuff } }); });

Categories : Ruby On Rails

Installing webkit for Capybara
There is no qmake utility on your workstation, as indicated by this message: Command 'qmake -spec win32-g++ ' not available I may suggest you to install QT for Windows. If this already done here suggested readings.

Categories : Ruby On Rails

what the best way for escape html with rails 4: gsub('<', '<') OR CGI.escapeHTML
The best way is probably to just assign the data to instance variables and then output them in the view, which will handle encoding automatically: controller: def something @foo = "<test>" end something.html.erb <%= @foo %> Will output: &lt;test&gt; The view will do the right thing in most cases.

Categories : Ruby On Rails

TypeError: no implicit conversion of Array into String
Try this = select_tag :ethnicity, options_for_select(['Asian', 'Black', 'Biracial', 'Indian', 'Hispanic/Latin', 'Middle Eastern', 'Native American', 'Pacific Islander', 'White', 'Other']) Note the options_for_select method Source

Categories : Ruby On Rails

Using .matches() on integer types
One of your problems is that the default index type in postgres is btree, and although it's pretty good at LIKE 'blah%', it's not very good at LIKE '%blah' [1]. To fix this, you should use a gist or gin index with the pg_trgm extension [2]. To install this, you should need to run the following command once on your database: create extension pg_trgm; Another is that you're comparing multiple c

Categories : Ruby On Rails

Rails 4 models managed through nested form -- do I need child controllers?
Ok, the QuestionsController is the active controller when questions are nested under surveys as in '/surveys/:id/questions'. Other than this (scoped questions#index) action, the SurveysController is in charge, which takes care of create/update/delete actions for itself and nested associations, questions and choices. Therefore, from my testing thus far, it appears that 1) the ChoicesController is

Categories : Ruby On Rails

How to select one option and display the results?
If you wanted to display it in the view without reloading the page you would need to write javascript for it. Otherwise, you would pass the selected option as a param to the index action and reload the whole page something like this (I'm making assumptions about a few things like the categories model having a name attribute): class LandingController < ApplicationController def index @cat

Categories : Ruby On Rails

Check box tag in rails always checked in nest form
Third argument to check_box_tag indicates if it should be checked or not So the following would make it render unchecked <%= check_box_tag "#{object.class.name.underscore}[audience_ids][]", audience.id, false, :class => 'audience' %><%= audience.name %> In edit, pass the value based on your attribute

Categories : Ruby On Rails

how to observe new or destroyed assocation in rails
Callbacks don't have to be defined on the association definition line. They can be added at any time to the associated object - especially if they are only added to this associated object. Here's a link to the docs on callbacks here To replace your after_add callback what you want is an after_create callback. and your after_remove you could use after_destroy eg: has_many :payments, as: :source

Categories : Ruby On Rails


Recently Add
Why isn't the confirm box working?
Polymorphic models (not associations!) in Rails
Link_to :Action won't call Controller Method -- Rails 4
Missing template when rendering a collection using local variables
rails simple_form using virtual attributes
uninitialized constant ActiveSupport::TestCase
Rails 4, Paperclip, S3 wrong url path
Neo4j gem - Updating relationship properties method
Error trying to deploy Rails app to Heroku
Modyfying before_action
CarrierWave TypeError (can't dump File) on Heroku
CanCan Ability in Rails - Giving partial manage
Uploading two images using s3 and paperclip on rails app
How to pass hash values of ActiveRecord::Base class
Ruby on rails. Heroku compile assets timeout when i add unicorn gem
Rails Template is Missing Error
Time.now.to_i different on heroku and locally
Simple rails app on Puma throws segfault, cannot handle concurrency
Setting Up Rails to Receive HTTP POST Request
Rails: Is it safe to use params[:bar] in link_to helper?
How to add aggregated columns from SQL SELECT to AR object in Rails
Circular Dependency Error autoloading constant
Groups and Users has many oder has many through?
Rails format specifier differences
Capistrano can not create symlinks: file exist
Admin can't delete users. Ruby on Rails 3 - Michael Hartl
Don't show user name who create post
Using Wicked with Devise (2 step signup process)
RubyOnRails Rake test failures
Rails session start event handler
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.