FAQ Database Discussion Community


capistrano deployment unable to bundle install gem with no internet connection

ruby-on-rails,ruby,ruby-on-rails-3,capistrano
I am deploying my application to a new server which has everything installed. I am using the following capistrano deploy.rb: require "capistrano/ext/multistage" require "bundler/capistrano" set :default_environment, { 'ORACLE_HOME' => "/opt/oraclient/64/11.2.0.2/", 'LD_LIBRARY_PATH' => "$ORACLE_HOME/lib:/usr/local/lib", 'PATH' => "/opt/ruby/bin:$PATH:$ORACLE_HOME/bin" } SECURE_FILES = ['database.yml', 'ldap.yml', 'initializers/secret_token.rb'] set :application, "myapp" set :use_sudo, false set :scm,...

Rails wrong number of arguments (1 for 0), ArgumentError in SubscribeController#update

ruby-on-rails,ruby,ruby-on-rails-3
I created a subscribe section using stripe. But I am having an issue with the routing. I'm not sure whats happening or what to do. Any help would be appreciated Migration to User Model class AddExtraDetailsToUser < ActiveRecord::Migration def change add_column :users, :subscribed, :boolean, :default => false add_column :users, :stripeid,...

Turbolinks, limit javascript to one page

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,turbolinks,highlight.js
I am using highlight.js and applying this code to initialise the syntax highlighting for my code snippets on a blog app. The following code is on my index.html page : <script> $(document).on('ready page:load', function() { $('pre code').each(function(i, e) {hljs.highlightBlock(e)}); }); </script> A code snippet should look like this originally: <pre><code>A...

Ruby on Rails require CSS error

css,ruby-on-rails,ruby-on-rails-3
I have a problem with Ruby on Rails rquire statements. I want to add a reset.css file before the require_tree. I have a application.css: /* *= require reset *= require_tree *= require_self . */ By doing this I am always gearing an error: wrong number of arguments (1 for 0)....

Rails submit create action succeeding

ruby-on-rails,ruby,ruby-on-rails-3
I am learning ruby rails and i have a #create problem (i think) when i am creating a new "stat" with form_for, once i press submit i get redirect to index.html.erb (as written in my controller) but there is no data apart from the id (even if i chose my...

Google authentification error “no route match”

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4
I have a problem, I follow this tutorial :https://richonrails.com/articles/google-authentication-in-ruby-on-rails. I have done everything except rails g controller home show because I have already a static_pages controller and home.html.erb So in my route.rb I have replace this line from the tutorial: resource :home, only: [:show] root to: "home#show" by resource :static_pages,...

Nokogiri parsing missing element create issue

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,nokogiri
I am having Plain html doc NO CSS . In which some of the content i need to pass to excel sheet. I tried with Nokogiri it works on Css basis. Do anybody tried this thing. <html> <head></head> <body> ***NOTE*** <br> Items <br> <br> Invoice Number : [78945824] PO Number...

Rails Convert UNIX timestamp to SQL DateTime

ruby-on-rails,ruby-on-rails-3,datetime
I have timestamp as "1432927800000" I want to save it in DateTime column of MySQL. (SQL DateTime column stores date in this format : 2010-06-24 11:30:00) I have tried uTime = params[:fromDate] #contains "1432927800000" Date.new(uTime).to_formatted_s(:db) #Comparison of String with 0 failed. DateTime.strptime("1318996912",'%s') #Give weird date: Wed, 03 Sep 47377 12:00:00...

assigning parent_id from an existing attribute

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,ruby-on-rails-3.2
I have a database that is imported from a CSV file and I would like to assign hierarchy based on the assembly level below. not sure which approach to take. I can write if statements but it will be very long. sorry I am new to this, and I don't...

Sorting a Rails active record

ruby-on-rails,ruby-on-rails-3,postgresql,sorting
I have a table A(:name, :address, :country_id). I run this query ids = [1,2,3] @result = A.where(country_id: ids) But, I want to get the results in this order : records containing country_id = 2 first, then 1 and then 3. How should I write this query? Edit : @people =...

Rails: ActiveRecord::RecordNotFound in Cart

ruby-on-rails,ruby,ruby-on-rails-3,activerecord
I user friendly_id for all the items. I am getting an error in the cart.rb model saying .. Couldn't find Product with 'id'=the-pen I'm unsure what to do. Any help would be appreciated cart.rb class CartItem < ActiveRecord::Base attr_reader :product_id, :quantity def initialize product_id, quantity = 1 @product_id = product_id...

has_and_belongs_to_many loads wrong resource

ruby-on-rails,ruby,ruby-on-rails-3,activerecord
I have 3 models # generic one class Someone < ActiveRecord::Base end # customer class Customer < Someone has_and_belongs_to_many :groups, join_table: "some_join_table", class_name: "Group" end # custom group class Group < GenericGroup has_and_belongs_to_many :customers, join_table: 'some_join_table', class_name: "Customer" end Let's assume that database is feeded. When i execute command Customer.first.groups...

What is causing NoMethodError in my CRUD?

ruby-on-rails,ruby,ruby-on-rails-3
I am student working on my first project on my own. The user is supposed to be able to create a to-do list. I have my form partial displayed and am trying to now render the list items through a partial. After altering my routes.rb and items_controller.rb I still receive...

How to configure Rails 3 app hosted on sub-url with Puma and nginx?

ruby-on-rails-3,nginx,puma
With Phusion Passenger, there are specific directives to use in the nginx virtual host configuration that allow Rails apps to be hosted on sub-urls. This is described in the Phusion Passenger documentation. With Puma, I am using sockets. My nginx config includes: upstream subapp { server unix:<path_to_subapp_folder>/shared/sockets/puma.sock fail_timeout=0; } server...

Apply an 'or' to an inner joined where clause ActiveRecord

ruby-on-rails,ruby-on-rails-3,activerecord,ruby-on-rails-3.2,rails-activerecord
Model: class QueueList < ActiveRecord::Base has_many :times self.today joins(:times).where(times: { period_type: 'on', date: Date.today} || times: { period_type: 'from', date: Date.today }) end end The above model contains a list of times. Because :times can be in two different period_types, I have to apply an "OR" to this query. Is...

generating a row depending on 5 distinct tables rails 3.0.1 ruby 1.8.7

mysql,ruby-on-rails-3
i have to generate a report that needs to compare data from 5 tables (User,Order,Product,Rating,OrderProduct) like this: User has many Orders (user_id in Order) Product has many children of itself through the field father_id User and Products has many Ratings (user_id and product_id in Rating) Order and Product has many...

Cannot run elastic search in circleci to make my rspec for elasticsearch to pass?

ruby-on-rails-3,github,rspec,elasticsearch,circleci
i have configured my project in github with circleci. I am using searchkick for elastic search. my code to reindex looks like this: IN spec_helper.rb RSpec.configure do |config| .... config.before :each do Location.reindex end ... end My app/models/location.rb looks like this class Location < ActiveRecord::Base ... searchkick word_start: [:location_name], autocomplete:...

Rails s and bundle install error with pg gem?

ruby-on-rails,ruby,ruby-on-rails-3,devise,gem
I am trying to install Ruby on Rails on my MacBook Pro running Yosemite 10.10 for my school program. I have installed everything successfully but now when I run rails s I get this error. I have tried to continue with bundle install to solve the issue but as you...

How do I update create route from rails 3 to 4

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4
I have a form tag which is seen below, when I try to run the page I get the error: No route matches {:action=>"create", :type=>"new", :controller=>"lists"} <%= form_for @list, :url => {:action => "create", :type => "new"}, :html => {:multipart => true,:role=>"form"} do |f| %> In my routes file i...

Ruby on Rails : How to find a matching value in JSON arrays?

arrays,ruby,json,ruby-on-rails-3,erb
irb(main):001:0> d = OurDomains.find(3) => #<OurDomains:0x000000056ea410 @id="2", @internal_domains=["1.com", "2.com", "3.com"], @external_domains=["2.com"]> Using the above response as an example, could someone give me a guide on how to compare values in the internal_domains and external_domains array please? Specially, I am interested in displaying all the values in internal_domains that corresponds to...

Rails can't render JSON undefined method `new' for nil:NilClass

ruby-on-rails,ruby,json,ruby-on-rails-3,postgresql
Background I'm making a Rails application which has two namespaces, which are admin (for administrator purpose) and api for mobile & web client. A weird thing happened yesterday. I made a new table facilities which consists of id, name, created_at, updated_at in my PostgreSQL database. Problem I tried to get...

why “Completed 406 Not Acceptable” has gone after removing respond_to?

ruby-on-rails,ruby-on-rails-3
when I used $.ajax() to submit the form's content with the following respond_to block: respond_to do render :json => { :url => question_path(resource, :recent => :true), :uploadPath => question_path(@question, :format => "json"), :editPath => edit_question_path(@question), :exitPath => question_path(resource) } end I got a error: Completed 406 Not Acceptable in 124690.7ms...

Rails can't find installed gem

ruby-on-rails,ruby,ruby-on-rails-3,railstutorial.org
I'm following a tutorial for Rails that specifically asks for version 4.2.0 so I installed Rails with sudo gem install rails -v 4.2.0 and it worked fine. When I try to create a new application with rails _4.2.0 new test_app I get an error message that says /Library/Ruby/Site/2.0.0/rubygems/dependency.rb.315: in 'to_specs':...

ruby on rails devise gem where is the database

ruby-on-rails,ruby,ruby-on-rails-3,sqlite,devise
I followed this tutorial: https://github.com/plataformatec/devise Everything works. I create a new user in the page: email, password, works fine. I can login with the password and email, I just wanna know where it is saving that, I tried find the sqlite database but I could not find anything. $sqlite3 sqlite>...

Ruby: When to use self and when not to?

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,ruby-2.0
I understand what Ruby self means, and I was trying to solve certain challenges on Tealeaf: http://www.gotealeaf.com/books/oo_workbook/read/intermediate_quiz_1 Here is the actual problem: Snippet 1: class BankAccount def initialize(starting_balance) @balance = starting_balance end # balance method can be replaced with attr_reader :balance def balance @balance end def positive_balance? balance >= 0...

Jruby: How to use third party java library?

ruby-on-rails-3,jruby
I want to use java third party qr code libary https://github.com/kenglxn/QRGen library for generating qr code. Please guide me as i don't know how to integrate java library in jruby....

ApplicationController helper method undefined in Rails

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4
I'm trying to write a simple helper method that checks if a user's email address contains a specific domain name. The method is needed in all my controllers and depends on the state of current_user, so I felt the best place to put it would be in my ApplicationController. Depending...

Find a Portion of a Database in Ruby

ruby,database,ruby-on-rails-3,object,where
Say for example I have the following database of instances of a class called Obj: | id | attr1 | +----+-------+ | 10 | A | | 15 | B | | 20 | C | | 50 | D | Now let's say I want to find all of...

Create new route Rails 4

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,routes
I have a problem: I want do decrement the quantity of a product of a line_item I use a button_to to decrement the quantity (the cart will be updated by AJAX) Btw , i' m not able to create a new action in the controller of line_items. I created the...

Rails 4 collection_select is MVC violated?

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,collection-select
I have a small question about collection_select in Rails 4. When we call in the collection_select all the elements of a table example: <%= f.collection_select :category_id, Category.all, :id, :name %> Is MVC violated? In other words: if I have a collection_select in the view of products and it calls Category.all...

Passing params without nil

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,search,params
I want to pass the value of a form to a Controller that should call a method from the Model for searching products i want to pass category_id and the string that the user writes in the textfield. I would pass to the model even the blank value of params...

Testing Rails Controllers and Middleware- Functional vs. Integration testing?

ruby-on-rails-3,unit-testing,integration-testing
Background I have a legacy Rails 3.2 app which I'm converting from a homegrown testing solution to a rails one (currently MiniTest). The app is a JSON api with a single endpoint, so testing is very simple at this point. We build a (relatively complex) json payload and then make...

How would you add Active Admin index columns from a sibling table?

ruby-on-rails-3,activeadmin
In my Customers_Rewards active admin I currently display columns from the Customer_Rewards and Customer data table, but I also want to display columns (such as store_id) from the Order data table. ActiveAdmin.register CustomerReward do menu :parent=>"Customers", :priority=>10, :label=>"Activated Rewards" index do selectable_column column("Customer ID"){|u| u.customer.id } column("Store ID"){|u| u.order.store_id }...

It shows nil in the database, can this solve the main issue?

ruby-on-rails,ruby-on-rails-3
If a seller sells something, I'm unable to show the user who bought it. With a Sale, Product, and User models <% @sales.each do |sale| %> <tr> <td><%= link_to sale.product.title, pickup_path(sale.guid) %></td> <td><%= time_ago_in_words(sale.created_at) %> ago</td> <td><%= sale.seller_email %></td> <td><%= sale.amount %></td> If I go ahead and change it to...

Sum returns value when should return 0

ruby-on-rails,ruby-on-rails-3
I'm having a really confusing problem. Here it is: [12] pry(EstimatedTime)> EstimatedTime.where(user_id: User.current.id, plan_on: date).pluck(:hours) => [] [13] pry(EstimatedTime)> EstimatedTime.where(user_id: User.current.id, plan_on: date).sum(:hours) => 3.0 What kind of magic is this? This statement resides in model method, that is being called from view. Before that, in controller action, i'm calling...

Rails: NoMethodError, how do I show users profiles?

ruby-on-rails,ruby,ruby-on-rails-3
When I type at the top, /users/1 or /users/2 I get the same page yet there are 2 users. It just redirects me back to show.html.rb page. I'm not sure but maybe I don't have a page for each user. Maybe you can look at my code. I am unable...

When does Devise actually send reconfirmation emails?

ruby-on-rails,ruby,ruby-on-rails-3,email,devise
I'm trying to add email confirmation to a model called "Project" in a Rails app: users should be able to set an email address for a project, which is not saved until they click a confirmation link sent to the email address provided. Although I have no need for its...

Ruby on Rails tags vs HTML tags

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,ruby-on-rails-3.2
I have a question about tags in .html.erb files. Which practice is better: Ruby on Rails tags or HTML tags? Is it better to use Ruby on Rails tags as much as possible? Or maybe I should avoid them and choose HTML ones instead? How to decide?...

Ruby on Rails 3 Multiple Associations

ruby-on-rails,ruby-on-rails-3,associations,polymorphic-associations
I have the following associations in place: class User < ActiveRecord::Base has_many :shopping_requests has_many :recommendations, :through => :shopping_requests end class ShoppingRequest < ActiveRecord::Base belongs_to :user has_many :recommendations end class Recommendation < ActiveRecord::Base belongs_to :shopping_request has_one :user, :through => :shopping_requests end Now I need to add a Compliment class. A user...

Print variables coming to model's methods

ruby-on-rails,ruby,ruby-on-rails-3,console
Having following code: class MyModel < ActiveRecord::Base before_create :do_process def do_process #I want to print here everything that came to this method self.my_stuff = my_stuff end Say we have model with name and description attributes and I'm going into console and enter something like MyModel.create! name: 'test', description: 'test' So...

how to get a response of running an API on remote rails server from another rails application

ruby-on-rails,ruby,ruby-on-rails-3
I have to rails application, my aim is to call an API on remote rails application and get back the result of that API. for example: 1st Application has update() API which does some processing and create a hash called data Now I want to call update() from 2nd Application...

Can we rename a resource collection/member URL?

ruby-on-rails,ruby-on-rails-3
I have this resource in routes.rb resources :orders, only:[] do collection do post :user_order_confirmation end end which creates a path like this in HTML views 'orders/carrier_order_confirmation'. Can we do something that this path looks like this 'orders/user_confirmation'?...

Heroku RAM not increasing with upgraded dynos

ruby-on-rails,ruby,ruby-on-rails-3,memory,heroku
I have a massive function i have been calling manually through the heroku rails console. I have been receiving the error rapid fire in my logs: 2015-06-22T14:56:42.940517+00:00 heroku[run.9877]: Process running mem=575M(112.4%) 2015-06-22T14:56:42.940517+00:00 heroku[run.9877]: Error R14 (Memory quota exceeded) A 1X dyno is suppose to have 512 MB of RAM. I...

whenever gem not working, Rails 4

ruby-on-rails,ruby,ruby-on-rails-3,cron,whenever
I am using Whenever gem to schedule some work on my site. Currently I am working on development environment. I have instaled gem as guide suggests. In schedule.rb every 2.minutes do rake "vip_recomend:give" end In lib/tasks/vip_recomend.rake namespace :vip_recomend do desc "Give vip recomend to ads that are in waiting list"...

Find Value by position on plain HTML in ruby

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-3.1,nokogiri
My Html file is not having any classes . I am trying to get the no. from the plain Html <html> <head></head> <body> PO Number : [4587958] </body> </html> I am able to find out the PO Number test by using require 'rubygems' require 'nokogiri' PAGE_URL = "a.html" page =...

Give argument to action on Rails

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-3.1
How do I give an argument to my action of a controller. I have an action named action and a controller named controller. I want to give an argument to the action when I go to http://localhost:3000/controller/action/argument1 or to http://localhost:3000/controller/action/argument2 How do I know, which argument was actually passed in...

Creating a object with nested form rails

ruby,ruby-on-rails-3,ruby-on-rails-4,nested-forms
I have 3 tables: members, meetings, meeting_has_members. The models are: member.rb class Member < ActiveRecord::Base has_many :meeting_has_members has_many :meetings, through: :meeting_has_members accepts_nested_attributes_for :meeting_has_members accepts_nested_attributes_for :meetings meeting.rb class Meeting < ActiveRecord::Base has_many :meeting_has_members has_many :members, through: :meeting_has_members accepts_nested_attributes_for :meeting_has_members accepts_nested_attributes_for :members meeting_has_member.rb class...

Cross-Domain iFrame Tracking with Google Analytics

html,ruby-on-rails,ruby-on-rails-3,iframe,google-analytics
I have a site (rails 3.2) that displays 3rd party news articles within an iframe. One page contains one iframe. I have Google Analytics setup. For this I use segment.io. The tracking script is in the head section of the container page. We have no affiliation with the 3rd party...

RestClient::RequestTimeout in controller#method ruby on rails

ruby-on-rails,ruby,ruby-on-rails-3,rest-client
I am making the following rest get request: rest_user = JSON.parse(RestClient.get APP_CONFIG['api_url'] + "users/", :params => {:token => APP_CONFIG['token'], :full => 'true'} )["users"] I get the following error back after a minute: RestClient::RequestTimeout in controller#method rbenv/versions/1.8.7-p374/lib/ruby/gems/1.8/gems/rest-client-1.6.7/lib/restclient/request.rb:184:in `transmit' rbenv/versions/1.8.7-p374/lib/ruby/gems/1.8/gems/rest-client-1.6.7/lib/restclient/request.rb:64:in `execute'...

Twitter Boostrap in Rails

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,twitter-bootstrap-3,rubygems
I generated views using this command rails g bootstrap:themed Todo it generated several views for my model. I am using git and reverted the project to its former branch without the boostrap. Now, I am trying to regenerate the views but it always returns this identical app/views/manifests/index.html.erb How do I...

How to load css in public files

ruby-on-rails-3
On my project i have following routes (routes.rb) resources :main, path: '/' do collection do get 'about' get 'blog' get 'resources' get 'contact' get 'projects-and-tutorials' end end and these routes are loading files from public folder like about.html and contact.html, right now no css file is loaded on these pages....

rspec controller empty session

ruby-on-rails-3,testing,rspec,controller
app/controllers/new_controller.rb: class NewController < ApplicationController def enter_time session[:dr] = 'dr' if !params[:time].nil? then Time.zone = @franchise.time_zone inanhour = 1.hour.since(Time.zone.now) delivery_time = delivery_time_format(params[:time]) delivery_time = delivery_time.change(offset: (Time.zone.now.utc_offset / 3600).to_s) session[:target_time] = [delivery_time, inanhour].max.to_s end end end spec/controllers/new_controller_spec.rb: require 'spec_helper' describe NewController, :type => :controller do...

Rails app trying to update a nonexistent column

ruby-on-rails,ruby-on-rails-3,postgresql
This is on Ruby 1.9.3 and Rails 3.2.19. I'm not super experienced with Rails. Today I started having this issue ONLY on our live server, everything works fine on the development server. Whenever I try to give a publication model new tags, I get this error: ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column...

Remove duplicates from custom search query

sql,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,acts-as-taggable-on
I have a search method that combines the results from doing a fuzzy search using the fuzzily gem and doing a search in the tags used in acts_on_taggable gem. if params[:search] results = Post.find_by_fuzzy_title(params[:search]) tagged_results = Post.tagged_with("#{params[:search]}") @posts = (Kaminari.paginate_array(results+tagged_results)).page(params[:page]).per(1) else The problem is that the returned query contains a...

rvm installation gpg key warning

ruby-on-rails,ruby,ruby-on-rails-3,rvm,gnupg
To install rvm, I use the command provided on the rvm website (https://rvm.io/rvm/install) to install stable versions of rvm: \curl -sSL https://get.rvm.io | bash -s stable --ruby I am a little concerned about the warning I get from gpg: "There is no indication that the signature belongs to the owner."...

Rails new app display error

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4
I am trying to create new project using rails but it display error. I am working on mac and its display error. $rails new EMS /Users/.rvm/gems/ruby-2.2.0/bin/rails:23:in `load': cannot load such file -- /Users/.rvm/gems/ruby-2.2.0/gems/rails-4.2.0/bin/rails (LoadError) from /Users/.rvm/gems/ruby-2.2.0/bin/rails:23:in `<main>' from /Users/.rvm/gems/ruby-2.2.0/bin/ruby_executable_hooks:15:in `eval' from /Users/.rvm/gems/ruby-2.2.0/bin/ruby_executable_hooks:15:in `<main>' ...

devise not redirect after sign in

ruby-on-rails,ruby,ruby-on-rails-3,devise
i am new in rails world, i would like a little help, i run devise gem and works perfect, i just have a small problem after sign in, i am not get the page a want and always redirect to my index page, can you guys give a little help?...

Rails 3 helper for match route

ruby-on-rails,ruby-on-rails-3,rails-routing
In a rails 3 application following match route is defined in routes.rb match 'accounts/:account_type/:account_id/edit_account' => 'accounts#edit_account' In controller i redirect to this URL redirect_to "/accounts/account/#{account_id.to_s}/edit_account" It works fine but i need a route helper instead of manually building the URL something like this edit_account_accounts_path(account_id: id, account_type: 'some_type') Is there any...

Rails : error param is missing or the value is empty : annonce

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,active-form
I want to creat a classified ads website for a project in school and I try to create a form to send a message by email at a member of the website. The email adress is contained in a model which is name "Membre" and this model is link at...

Unicorn+Nginx concurrency and data duplication

ruby-on-rails,ruby-on-rails-3,nginx,concurrency,unicorn
I have 4 Nginx workers and 4 unicorn workers. We hit a concurrency issue in some of our models that validate unique names. We are getting duplicated names when we send multiple requests at the same time on the same resource. For instance if we send around 10 requests to...

Ruby on Rails ActiveRecord Conventions

ruby-on-rails,ruby,ruby-on-rails-3,activerecord
We're trying to establish best practices for a project and we're discussing where SQL and ActiveRecord methods should be placed. My understanding is that you want to keep as much logic out of controller as possible. I think we agree on complex SQL queries belonging to models, but we are...

Devise nested attributes form field not showing

ruby-on-rails,ruby,forms,ruby-on-rails-3,devise
I am having trouble viewing the nested attributes field in my form. I am in the jobs/new view and I want have a User form that creates a job as well as a user. I have everything in this answer Rails 4.0 with Devise. Nested attributes Unpermited parameters I have...

Openshift how to create a table on ruby on rails application? via console

ruby,ruby-on-rails-3,ruby-on-rails-4,openshift
Openshift how to create a table on ruby on rails application? via console I'have a gem installed called 'rhc', but how can I create a table for a ruby on rails application via rhc command? https://www.openshift.com...

Why Rails instance method can be used as class method in rspec

ruby-on-rails,ruby,ruby-on-rails-3,rspec,actionmailer
I found a snippet in an article about sending mails in a Rails application: class ExampleMailerPreview < ActionMailer::Preview def sample_mail_preview ExampleMailer.sample_email(User.first) end end in this link: http://www.gotealeaf.com/blog/handling-emails-in-rails. I do not know why the method: sample_email(), which in my mind should be an instance method, can be accessed like class method...

controller logic for two different type of users

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,model-view-controller,controller
In my project i have three different categories of users: Guest Registered Admin If a Registered user is logged , i want to show him (if he clicks on a button) his orders. The admin , instead , can see the orders of the other users. I can use OrderController...

how validation is done using wicked?

ruby-on-rails,ruby-on-rails-3,wicked-pdf
I have a users_controller and a user_steps_controller which has three steps :business, :payment and :login In the user.rb model class User < ActiveRecord::Base validates_presence_of :fname, :lname, :email, :mob, :country, :state, :suburb, :postal ,:add end while checking validation if i put some random values then also it is giving errors Fname...

Hide label in certain resolution with simple_form

ruby-on-rails-3,twitter-bootstrap,simple-form
I have this wrapper in simple_forms config.wrappers :styled_horizontal_boolean3, tag: 'div', class: 'form-group', error_class: 'has-error' do |b| b.use :html5 b.optional :readonly b.use :label, class: 'hidden-sm hidden-xs col-md-3 control-label' b.wrapper tag: 'div', class: 'col-md-9 checkbox-margin' do |wr| wr.wrapper tag: 'div', class: 'styled checkbox' do |ba| ba.use :label_span_input, class: 'col-md-9', span_class: 'left' end...

regex not matching periods followed or preceded by letters - ruby

ruby,regex,ruby-on-rails-3
This is a method I'm using to slug the title of an article. The problem is I'm getting an error with any title that has a "." followed or preceded letters. For example "example.com", "U.S." doesn't match. However it works when using numbers. def self.to_slug(str) #strip the string ret =...

ActiveRecord Group by 2 columns

ruby-on-rails,ruby-on-rails-3,activerecord
Message model user_id # owner of the message sender_id # user that sent message receiver_id # user then recieved message content # content of message I have Messages. I would like to group them by sender_id and receiver_id as these are a "conversation thread". When I do group I get...

Nested forms/models: return only records belonging to current_user

ruby-on-rails,ruby-on-rails-3
I have a music reviews site and there are 3 admins. Whenever we go to edit an album, it pulls in the nested forms for reviews and, if there are any, it shows all review records on albums#edit regardless of who the author/owner of a given record is. How can...

Is there any way to print a database content in a pretty syntax?

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4
I have a simple database in ruby on rail and i want to know if there is a way to display properly the result of a request in ruby. For example in a base which is like this : User(id, name, email) whith a content like that : (1, jack,...

Rails 3 join where query - print only on row

ruby-on-rails,ruby,ruby-on-rails-3
I have two models, Campaigns and Orders I would like to find a specific campaign with it orders and print all emails. I tried this in the console but get all the orders data when I only want the row :email Campaign.find_by_id(46).orders(:email) How to print only the emails of those...

How can I dynamically define a source for an ActiveRecord has_many relation?

ruby-on-rails,ruby-on-rails-3,activerecord
Given the ActiveRecord model below: class Model < ActiveRecord::Base has_many :group_assignments has_many :product_assignments # Only one of the next two should appear, based on condition has_many :products, through: :product_assignments has_many :products, through: :group_assignments end Would like to define the last has_many...through relation based on the following condition: if the model...

Deletion assignment, undefined method `avatar?' for nil:NilClass

ruby-on-rails,ruby,ruby-on-rails-3,carrierwave
I am a new student to Ruby on Rails and am currently working on the Deletion HTTP request for my project, a Reddit clone. So far I have implemented Destroy functionality on Topics and Posts successfully. Now that I am working on the deletion of Comments I have hit an...

Load associations to one level while conditionally sideloading associations in Active model serializers

ruby-on-rails-3,ruby-on-rails-3.2,active-model-serializers
AMS version 0.8.3, I created a base_serializer.rb like this and extended the same. class BaseSerializer < ActiveModel::Serializer def include_associations! if @options[:embed] embed = @options[:embed].split(',').map{|item| item.strip.to_sym} embed.each do |assoc| include! assoc if _associations.keys.include?(assoc) end end end end class EventSerializer < BaseSerializer attributes :id, :name has_many :organizers, serializer: OrganizerSerializer has_many :participants, serializer:...

extract `.for()` into a method

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4
I have a class like this one: class House def bricks Brick.for(@house_plan).where(size: 5) end def wood Wood.for(@house_plan).where(size: 5) end end My goal is to extract the call for(self).where(size: 5): What I tried first was: class House def bricks Brick.match_material end def wood Wood.match_material end def match_material for(@house_plan).where(size: 5) end end...

Form data not being sent in the email

html,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4
Below is code that I have that I basically just mimicked. A professional web developer made the website, so im just following how they did it. But, for some reason the data does not get sent in the email. But, the email does send. controller file def createproject @title =...

How can I stub a controller instance variable using RSpec?

ruby-on-rails-3,rspec,controller
new_controller_spec.rb require 'spec_helper' describe NewController do describe 'actions' do describe 'POST /franchise_opportunities' do it 'renders v3/franchise_opportunities when domain id 5' do domain = double(Domain, mrdeliverycom?: true) controller.instance_variable_set(:@domain, domain) post :franchise_opportunities, name: 'v' response.should render_template('v3/franchise_opportunities') end end end end new_controller.rb # -*- encoding : utf-8 -*- class NewController < ApplicationController before_filter...

Load fixtures in Rails

ruby-on-rails,ruby-on-rails-3,unit-testing
I am writing tests for a model Friends::New. My new_test.rb file looks like : require 'test_helper' class Friends::New < ActiveSupport::TestCase fixtures :news.yml end My news.yml is located in test/fixtures/friends/news.yml. But during running test, it tries to find news.yml in test/fixtures/. How do I tell it to search the yml file...

How to pass params to new view in Ruby on Rails app?

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,model-view-controller
I'm trying to make simple app. I input my first name and last name to simple <%= form_for @data do |f| %> rails form and after submitting it, app should render simple text like this. My first name is <%= data.first_name %> and my last name is <%= data.last_name %>....

Run a rails query in batches

ruby-on-rails,ruby-on-rails-3,performance,postgresql,cursor
I have a table A(:name, :address, :phone) consisting of 500,000 entries. I want to run this query : johns = A.where(:name => "John") This query should return 150,000 results. But running this query gives me this result : Killed. How should I rewrite this query so that the query runs...

Updating params in URL after forced/manual input

ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4
I am currently using the Devise user system to set up a model Tutor which is associated to a model Profile whereby Tutor has_one :profile and Profile belongs_to :tutor. Therefore a tutor_id foreign key associates each profile entry to a tutor entry. In the Profile model, I have the usual...

redircting error in ruby on rails

forms,ruby-on-rails-3
I'm new to ruby on rails. I tried to redirect to outlet_controller#map, but the below code redirect me to #show. what i am doing wrong. help me to sort out. my route is namespace :api do get 'outlet/map' => 'outlets#map' end my controller is class Api::OutletsController < ApplicationController http_basic_authenticate_with :name...

Sent emails with Action Mailer

ruby,ruby-on-rails-3,gmail,actionmailer
I am trying to send an email to [email protected] with Action Mailer (Ruby on Rails). The method sendactivation is correctly executed and the message "Email sent" is displayed. However, I never receive any email. Actually, the output "Test" is never printed. My webapp is hosted on Heroku Cedar-10. class UsersController...

Froala code snippet losing breaklines on edit

ruby-on-rails-3,ruby-on-rails-4,wysiwyg,pre,froala
I am making a simple blog in RoR. When I edit a post I am losing all linebreakes in the code snippet. How can I make sure that when I am reloading the content of the post, the editor correctly formats the code snippets? This is the input into the...

MVC Logic and Active Record example Rails

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,activerecord,model-view-controller
I want to ask two things: 1) In the MVC logic of Rails , is correct to call a Model into another Model? In other words: class A def function1 ... end end class B def function2 A.function1 end end This is just an example and there isn't any association...

The action 'Search' cannot be found for InboxController

ruby,ruby-on-rails-3
I am trying to add a search bar. I have also set the path. But everytime I try to click on search it directs me to this error. What is the error in this code? This is my Inbox_Controller file. It says that the action 'Search' cannot be found in...

RoR server for production

ruby-on-rails,ruby,ruby-on-rails-3
I'm new to Rails and am confused about running my RoR code on server (from linode.com). I have been developing my RoR application locally and I start my server using the rails server command. However, when I ported the same code to my server (git clone) and ran the command...

undefined method `refreshProfile_affinity_path' for #<#:0x8dbdc30>

ruby,ruby-on-rails-3,updates,put,undefined-function
I'm getting the error in the title. I am not sure how exactly to write the routes, controller, and index. I am trying to create a 'Refresh' button in an index.html.erb view shown below: ... <td><%= link_to 'Refresh', refreshProfile_affinity_path(a), method: :put %></td> ... It is using this route in routes.rb:...

Refactoring nested routes, how do I address this redirect_to?

ruby-on-rails,ruby,ruby-on-rails-3,routing,refactoring
I am working on an assignment for a project I have been working on. I was just introduced to refactoring my nested routes. Here are the changes. routes.rb resources :topics do resources :posts, except: [:index] do resources :comments, only: [:create, :destroy] end end to resources :topics do resources :posts, except:...

config.active_record.whitelist_attributes = false in Rails 4.2 App

ruby-on-rails-3,ruby-on-rails-4,strong-parameters
Our rails 4.2 app consists of several rails engines with or without gem 'protected_attributes'. What we find out is that in app's application.rb, it has to be: config.active_record.whitelist_attributes = false Otherwise, any create/update can not be carried out because the params can not be assigned to instance variable. Our question...

Where is Person and not Person::Single

ruby,ruby-on-rails-3,ruby-on-rails-4
Lets say I have three Classes Person Person::Single < Person Person::Married < Person Lets say I have two Persons that are Single => Person::Single Then i get two Persons when I do: Person.all.count => 2 But my goal is to get only the persons that are type Person and not...

How to store nil with Rails.cache.fetch & memcache?

ruby-on-rails,ruby-on-rails-3,caching,null,memcached
I have an existing Model singleton method triggering expensive database queries that I want to model cache. To do this, I wrapped a Rails.cache.fetch() call around the method in question: # app/models/specialist.rb class Specialist < ActiveRecord::Base def city Rails.cache.fetch([self.class.name, self.id, "city"], expires_in: 23.hours) do # expensive legacy query: if responded?...

How to represent serialized fields in ActiveRecord::Base in ActiveRecord:Migration (Rails 2.3.16)

ruby-on-rails,ruby,ruby-on-rails-3,activerecord
I'm new in rails. I read rencently how to serialize an array of string for example to store it in database. class Fle < ActiveRecord::Base serialze :etat_fle end But i don't know how to represent this serialized field in the corresponding ActiveRecord::Migration Have someone an idea ?...

Multiple Views Same Model

ruby-on-rails,ruby,ruby-on-rails-3
I have a Course Model which goes the controller and views in a restful way. For my Course show, it is fully featured. I now want another Course show which will have a simplify page and it like to the original course show. How can I implement this? I want...

Iterate through several objects form_for rails

ruby-on-rails,ruby,ruby-on-rails-3,form-for
Executive Summary Goal: I am creating an admin dashboard, editable by a form_for I have a Post model which has two attributes: Subject and Title I have created an Admin Controller, which has an index action I get an error claiming it can't find the undefined method `subject' for ActionView:FormBuilder:0x000000031e02c8>...

Rails - How to find tilt version?

ruby-on-rails-3,ruby-on-rails-4,sprockets,tilt
Gem tilt is used with sprockets for Rails assets precompile. We are having hard time to find the version running on our Rails 4 app as tilt --version returns version unknown: $ tilt --version tilt: version unknown tilt --help give no info about how to find version. Is there way...

Limit the amount of results in associated queries with Rails 3.2

sql,ruby-on-rails-3,activerecord
I have the following query: @books = Books.includes(:author, :pages) .find(:all, :order => 'created_at DESC') Let's assume my "Pages" table has fields "words, pictures". For blank pages, field "words" is NULL. There are many "Pages" records per book. The problem with the above query, is that it retrieves ALL the pages...

get count of has_many association in rails query

mysql,ruby-on-rails-3,model-associations
I have a two model. Post and `Comment'. Post has_may comments. Query: I want to get the max count of comments in which post. This should be done by rail query....

Custom Search in Ruby on Rails

mysql,ruby-on-rails,ruby,ruby-on-rails-3
I'm trying to implement a custom search feature in my Rails app. I have 3 tables User Company and CompanyUser My relations declared are as follows class CompanyUser < ActiveRecord::Base belongs_to :company belongs_to :user ... end In Company.rb has_many :company_users, dependent: :destroy has_many :users, through: :company_users In User.rb has_many :company_users,...