FAQ Database Discussion Community


How to find a record from database by using find_by with two fields?

ruby-on-rails
I want to find a record from database in ruby on rails by using find_by with two fields. How can I accomplish it?

Active Record Where Clause For Relation In Model

ruby-on-rails,activerecord
I have two Models User and Site. The User has category like 'basic and premium'. The user has relation to sites one -> many (i.e one user can have more than one sites). Now i want to select sites of premium user. Can someone tell me how to use where...

Redirect if ActiveRecord::RecordNotUnique error exists

ruby-on-rails,postgresql,activerecord,error-handling
I have the next code to save: Transaction.create(:status => params[:st], :transaction_id => params[:tx], :purchased_at => Time.now).save! But how can I redirect to main root page if this ActiveRecord::RecordNotUnique error appears? Can I catch this error?...

One controller uses its corresponding layout, but the other does not

ruby-on-rails,layout
My Rails project has two controllers, a SessionsController and a CustomersController. My project also has two layout views in the layouts directory, sessions.html.erb and customers.html.erb. I would like the SessionsController to render using the session.html.erb layout and the CustomersController to render using the customers.html.erb layout. I have removed all explicit...

sqlite issue with heroku

ruby-on-rails,sqlite,heroku
I was using sqlite gem for my rails project, and since I had to put the app on Heroku, and Heroku doesn't support sqlite, I added pg gem to my Gemfile. gem 'pg', '0.17.1' But now I am not able to run the project locally on my machine. Specified 'sqlite3'...

Is there a way to get the `id` of a nested_form field helper element?

ruby-on-rails,nested-forms
I am trying to create the for attribute for a label in a nested form (Using nested_form). Is there a way to get the id of a corresponding f.checkbox? HAML: = label_tag '???', "Set as On", class: primary_btn = f.check_box :is_on Additional Information: The current Model structure is like Post...

Grab host app active record objects when engine and host app have same model names

ruby-on-rails,ruby
I have a host app unicorn with the model Article. I also have a mountable engine hooked into the host app called blorgh. It also has a model: Article. It is namespaced, so the table name for the engine's Article is actually blorgh_articles. While inside the engine I want to...

RSpec test for rake task

ruby-on-rails,ruby,rspec,rake-task
I have created a custom rake task that deletes all items that are >= 7 days old. I am trying to write a RSpec test for this new task but it seems like my task isn't really running in the test. I have tested the task manually and it works...

Can rspec be used to feature test an integrated rails-angular app?

ruby-on-rails,angularjs,rspec,capybara
I have a very basic, integrated rails-angular app. It just renders a link, which uses data from a get request to rails: 'use strict'; angular.module('angularRspec.controllers') .controller('FightersController', function($scope, $http){ console.log("FightersController is loaded..."); $scope.fighters = []; $http.get('./fighters.json'). success(function(data, status){ $scope.fighters = data; console.log(status); console.log(data); }). error(function(data, status, headers, config) { console.log(status); console.log(headers);...

rendering the partials in controller after the validation check

ruby-on-rails,ruby-on-rails-4,model-view-controller
I have two partial views for two different sign up forms. On my home page , based on the link one clicks on, I'm rendering respective form.(views/application/index) = link_to 'Mentor', new_user_path(user_role: true), :class =>'btn' = link_to 'Mentee', new_user_path, :class =>'btn' In views/users/new.html.haml , I'm checking the user role and redirecting...

Couldn't find User with 'id'=show

ruby-on-rails,ruby,devise
a Rails/Devise Question for you today. I'm working on user profiles for a site and I am hitting this error ActiveRecord::RecordNotFound at /users/show Couldn't find User with 'id'=show Not sure exactly what's happening as I haven't really run into anything like this before. Here are some necessary files to take...

RoR: removing sensitive field from response

ruby-on-rails,ruby,rails-activerecord
Is there any way to remove sensitive fields from the result set produced by the default ActiveRecord 'all', 'where', 'find', etc? In a small project that I'm using to learn ruby I've a reference to User in every object, but for security reasons I don't want to expose the user's...

Same enum values for multiple columns

ruby-on-rails,ruby,enums
I need to do something like this: class PlanetEdge < ActiveRecord::Base enum :first_planet [ :earth, :mars, :jupiter] enum :second_planet [ :earth, :mars, :jupiter] end Where my table is a table of edges but each vertex is an integer. However, it seems the abvove is not possible in rails. What might...

Rails Association Guidance [on hold]

ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2
I am new to rails 4. I have gone through lots of tutorials and trying to solve below scenario. But still no success. Can anybody point me in the right direction. How to handle associations for below scenario. Scenario: 1. Patient can have many surgeries. 2. Surgery has two types...

Rails 4 - Javascript - trouble with .not()

javascript,jquery,html,ruby-on-rails,ruby-on-rails-4
Can someone tell me what is wrong in this Javascript ? It's supposed to show an alert "already opened" if there's plus (or) 2 PP div with a class "open". if ($('PP').not('.closed')>=2) { window.alert('already opened'); } ...

Is it possible to have two callbacks in around_destroy in rails?

ruby-on-rails,activerecord,callback
Although this can be accomplished as follows: class Model < ActiveRecord::Base around_destroy :callback def callback puts 'callback1 before yield' puts 'callback2 before yield' yield puts 'callback1 after yield' puts 'callback2 after yield' end end But I wish to do the following: class Model < ActiveRecord::Base around_destroy :callback1, :callback2 def callback1...

Rails: Posting from a form to a M:M table

ruby-on-rails,activerecord
On the group index page I display a listing of group discussions and a form to create a new discussion. class Group < ActiveRecord::Base has_many :discussions end class Discussion < ActiveRecord::Base belongs_to :user belongs_to :group end Controller: class DiscussionsController < ApplicationController def index @group = Group.find(params[:group_id]) @discussion = current_user.discussions.build({group_id: @group.id})...

Rails - searching in the console

ruby-on-rails,rails-console
I am trying to make an app with Rails 4 and Simple Form. I have three models, being: Project, Scope and Background. Project has one scope. Scope has one background. Scope belongs to project. Background belongs to scope. Project accepts nested attributes for Scope. Scope accepts nested attributes for background....

Can Rails deal with DB uniqueness without index?

mysql,ruby-on-rails,rdbms
I see add_index ~ unique: true statement in schema.rband think uniqueness is constraint for table, not for index.Using index is one of way realizing uniqueness, Programmer should not designate to the RDBMS "how" and index quicken searching but take costs inserting. In fact, is there another way to keep uniqueness...

jQuery remove closest not working on elements added to DOM after page load

jquery,html,ruby-on-rails
I have the following Rails loop that lists all @team.authority_emails: <% if @team.nil? %> <% @team.authority_emails.collect.each_with_index do |a_e, index| %> <div class="row"> <div class="large-11 columns"> <input type="text" value="<%= a_e %>" name="authorities[]" class="authority-email"> </div> <div class="large-1 columns"> <a href="#" class="remove"><%= icon('fa fa-remove') %></a> </div> </div> <% end %> <% end %>...

Elasticsearch advanced search

ruby-on-rails,ruby,search
I find Elasticsearch gem and want to use it. For example I have: Method in app/controller/search_controller.rb: def search if params[:q].nil? @articles = [] else @articles = Article.search params[:q] end end View at app/views/search/search.html.erb: <h1>Articles Search</h1> <%= form_for search_path, method: :get do |f| %> <p> <%= f.label "Search for" %> <%=...

Rails, Simple Form, Nested Forms

ruby-on-rails,simple-form
class Project has_many :project_questions, dependent: :destroy#, through: :projects accepts_nested_attributes_for :project_questions end I am trying to make an app with rails 4 and Simple Form. I have models called projects, project_questions and project_answers. The associations between them are: Projects: has_many :project_questions, dependent: :destroy#, through: :projects accepts_nested_attributes_for :project_questions Project questions: belongs_to :project#,...

Rails less url path change

ruby-on-rails,ruby,url,path,less
Developing a Rails application with the less-rails gem I found something unusual : // app/assets/common/css/desktop/typo.less @font-face{ font-family:'SomeFont'; src:url("fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); // ... } The requested font is app/assets/common/css/fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot This font is compiled with less and the results is : @font-face { font-family: 'SomeFont'; src: url("desktop/fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); //... } Do you know why is...

RESTful routing best practice when referencing current_user from route?

ruby-on-rails,rest
I have typical RESTful routes for a user: /user/:id /user/:id/edit /user/:id/newsfeed However the /user/:id/edit route can only be accessed when the id equals the current_user's id. As I only want the current_user to have access to edit its profile. I don't want other users able to edit profiles that don't...

adding link_to with image_tag and image path both

html,ruby-on-rails,image,ruby-on-rails-4,svg
I am trying to replace the tag with link_to in my rails application view. for replacing I have svg icon, text and link all in one tag. Here is below <a class="navbar-brand" href="index.html"><%= image_tag 'logo.svg', "data-svg-fallback" => image_path('logo.svg'), :align=> "left" ,:style => "padding-right: 5px;" %> My Project </a> but I...

How to convert a string into datetime format using rails?

ruby-on-rails
I am getting date and time from datetime picker and I want to store this into database. Database field type= datetime. I am using ruby on rails.

Active Record association links, but can't assign values

ruby-on-rails
I'm setting up permissions for each user to determine what access they have to certain data. I have a user model and a permission model that is set up with a has_many and belongs_to association like so: app/models/permission.rb class Permission < ActiveRecord::Base has_many :users end app/models/user.rb class User < ActiveRecord::Base...

Javascript not executing when using link_to

javascript,jquery,ruby-on-rails
I have couple javascript functions that attaching action to buttons in controller view some/index. I navigate to some/index using link_to method. But when i'm using link_to method, buttons has no attached javascript actions (in some/index view). When i try open some/index directly from my browser, buttons have all attached actions...

Showing and editing has_many objects in Rails

ruby-on-rails,ruby-on-rails-4
I'm trying to do something that I imagine to be very basic, but I'm very new to Rails and am not sure what sure what I'm doing wrong. I've gone through several tutorials and searched for an answer and can't find what the issue is. Would appreciate any help! I've...

Stack level too deep because recursion

ruby-on-rails,ruby,ruby-on-rails-4,twitter
I have a model named Tweet. The columns of the Tweet model are: -id -content -user_id -picture -group -original_tweet_id Every tweet can have one or multiple retweets. The relation happens with the help of original_tweet_id. All the tweets have original_tweet_id nil , whilst the retweets contain the id of the...

How to use Rails #update_attribute with array field?

ruby-on-rails,ruby,postgresql,ruby-on-rails-4,activerecord
Each question has an array of tags. schema.rb: create_table "questions", force: true do |t| t.text "tags", default: [], array: true How to atomically append to tags? How to prevent dups within the array? I tried question.update_attribute tags: tags << :ruby, but this doesn't work. Rails 4.17 and Postgres. EDIT: This...

Rspec view test with url parameters

ruby-on-rails,unit-testing,testing,rspec,rspec-rails
I have a page dashboard.html.erb that may be redirected to from several different controllers/actions. When it receives the redirect, it also receives several url parameters. Controller code: class PlansController def some_action redirect_to dashboard_path(show: "default", cool_array: ["test", "test"]) end end class StaticpagesController def dashboard end end View code: <% if cool_array...

RoR Tutorial Chapter 3 - Guard detects changes but doesn't fully execute tests

ruby-on-rails,railstutorial.org,minitest,guard
I'm currently following the book and the video and in the video, Hartl runs a guardfile so that it automatically runs tests after any changes have been made. So in the videos when he presses return whilst in guard mode, it says: 17:35:31 - INFO - Running: test/controllers/static_pages_controller_test.rb followed by...

CSS placing image by a form

html,css,ruby-on-rails,zurb-foundation-5
I want an image to appear right beside a form. This is what I am have tried. CSS file: .il { display:inline; padding: 0px; margin: 0px; } new.html.erb <div class="il"> <%= image_tag("successful_forex_trader.jpg", :alt => "Forex Money Manager") %> <div class="small-6 large-centered columns"> <%= form_for(@investor) do |f| %> <%= render 'shared/error_messages',...

Ruby on Rails - Help Adding Badges to Application

ruby-on-rails,ruby,rest,activerecord,one-to-many
I'm creating a rails application that is a backend for a mobile application. The backend is implemented with a RESTful web API. Currently I am trying to add gamification to the platform through the use of badges that can be earned by the user. Right now the badges are tied...

rails Initialize new object through associated search

ruby-on-rails
In my rails application I would like to be able to search for a client from the nav bar and have it automatically provide the WorkOrderController with the associated client. The goal is to automatically generate some of the work order information before the user gets to the new view....

ActiveAdmin ::Show 4 textbox in active admin using has_many relationship

ruby-on-rails,gem,activeadmin
I have one poll table having with question filed and each question have 4 answer which is has_many relation ship with answer table class Poll < ActiveRecord::Base has_many :answer end My answer model class Answer < ActiveRecord::Base belongs_to :poll, :class_name => "Poll", :foreign_key => "question_id" end My active admin form...

In Ruby how to put multiple lines in one guard clause?

ruby-on-rails,ruby
I have the following line of code : if params[:"available_#{district.id}"] == 'true' @deliverycharge = @product.deliverycharges.create!(districtrate_id: district.id) delivery_custom_price(district) end Rubocop highlight it and asks me to use a guard clause for it. How can I do it? EDIT : Rubocop highlighted the first line and gave this message Use a guard...

Rails shared controller actions

ruby-on-rails,ruby,ruby-on-rails-4
I am having trouble building a controller concern. I would like the concern to extend the classes available actions. Given I have the controller 'SamplesController' class SamplesController < ApplicationController include Searchable perform_search_on(Sample, handle: [ClothingType, Company, Collection, Color]) end I include the module 'Searchable' module Searchable extend ActiveSupport::Concern module ClassMethods def...

paper clip show image url is undefine

ruby-on-rails
I want to show image in each loop and image is upload by paperclip gem. The real path is /system/users/images/000/000/035/original/lovecupcake.jpg When i use this this is working fine rails code <%= image_tag @user.image.url(:medium) %> output <img alt="Lovecupcake" src="/system/users/images/000/000/035/original/lovecupcake.jpg"> it show me image but when i apply loop <% @result.each do...

Redirect Loop on Heroku with Rails 4 App, but not on local machine

ruby-on-rails,ruby-on-rails-4,heroku,dns
App running Ruby 2.2.2, Rails 4.2.1 When I run my app locally everything is fine. It was running fine on heroku until I made some updates. Now all I get in a browser is "Err too many redirects" from Chrome, or "Too many redirects..." in Safari. Even after I rolled...

Heroku rake db:migrate failing - uninitialized constant

ruby-on-rails,ruby,heroku
My app is working fine locally and my push to Heroku was successful. But, when I run heroku run rake db:migrate, I get the following error: NameError: uninitialized constant AddWeightToExercises Here is the failed migration: class AddWeightToExercise < ActiveRecord::Migration def change add_column :exercises, :weight, :float end end edit: Thanks for...

Javascript Changing Random Background Image Issue

javascript,html,ruby-on-rails,ruby-on-rails-4,background-image
I am on Rails 4, and finally got this javascript working. It changes randomly changes the background image every 10 seconds with a fadein fadeout effect. The only issue is every so often, an image will only load halfway... then it will start to flash and and get crazy. It...

Loop through list of AWS-instances shows only first item

ruby-on-rails,amazon-web-services,amazon-ec2,each,aws-sdk
I am working on a simple customer frontend for AWS. I want a list of all the users machines for start/stopping the EC2s. While the logic works I can only show the first of the machines in my view. I guess it's related to the AWS APIs pageable response format,...

How to exclude guest users from getting emailed Rails 4 Devise

ruby-on-rails,email,ruby-on-rails-4,devise,mailer
Just set up my first mailer on Rails 4. I have a welcome email sent to new users as soon as they sign up (create) for a new account using devise. I also have devise set up so that if a current_user is not found, a guest user will be...

Sorting in Ruby on rails

ruby-on-rails,json,sorting
I'm very new to Ruby on rails. I try to edit the following api. I want to sorting "can_go" which is true are shown at the top of list. I added this row before sending data, but the result is still order by "user_id". user_infos.sort { |a, b| - (a['can_go']<=>b['can_go'])...

Broken Rails integration after moving 'micropost feed' - Expected at least 1 element matching “div#error_explanation”, found 0

ruby-on-rails,integration-testing
After following Michael Hartl's Rails Tutorial I moved the 'micropost feed' from / to /members, and now when I submit a post that doesn't validate properly (too many characters, missing content etc.) rails returns an error saying: ArgumentError in MicropostsController#create First argument in form cannot contain nil or be empty...

Can't map a range of dates in Ruby/Rails

ruby-on-rails,ruby
I'm trying to map a range of dates and pass them to my view as an array, as follows: from, to = Date.parse("2014-01-01"), Date.yesterday date_range = (from..to) @mapped_dates = date_range.map {|date| date.strftime("%b %e")} I reference them in some JS in my view as follows: dateLabels = <%= raw @mapped_dates.to_json %>;...

Error when trying to install app with mysql2 gem

mysql,ruby-on-rails,ruby,ruby-on-rails-4
Im trying to install an open source rails 3.2.21 application that uses the mysql2 gem, but when i try and run the bundle commant I get the following error: Fetching: mysql2-0.3.18.gem (100%) Building native extensions. This could take a while... p ERROR: Error installing mysql2: ERROR: Failed to build gem...

How to validate non-db attributes on an ActiveRecord model?

ruby-on-rails,validation,activerecord
I have the following class: class Instance < ActiveRecord::Base attr_accessor :resolution validates_format_of :resolution, with: /\A\d+x{1}\d+\d/ def resolution=(res) validate! (set the resolution etc) end def resolution (get the resolution and return) end end The resolution attribute is not stored in the database, but is a transient property of the instance. When...

Sortable in Rails 4

ruby-on-rails,jquery-ui,ruby-on-rails-4
I'm following Railcasts #147 using Rails 4 instead of 3. The method below is not passing in Rails 4. So far all, all is working except for updating the databse with the new sorted position. Any idea how I can mass update the records? def sort params[:faq].each_with_index do |id, index|...

Rails4 + sunspot search

mysql,ruby-on-rails,solr,sunspot
I am trying to use sunspot solr for searching with Rails 4 and mysql. I defined a searchable block in my model(eg XYZ): searchable do text :name, :stored => true string :id, :stored => true end I just want to search in "name". The "id" is the primary key. There...

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...

how to get validated the associated attributes? rails4

ruby-on-rails,validation
I am using rails4. I have a model, lets say human. Human has nested model Man. Man has attributes Name, Address, Number. I am trying to make an api in which i am not able to validate associated attributes. I was able to validate the man by using validates_associated, But...

Undefined local variable post

ruby-on-rails,ruby,variables,undefined,local
I write this code: <% @user.posts.each do |post| %> <%= render 'post', locals: { post: post, user: @user} %> <% end %> Then in _post.htm.erb I write follow code: <div class="post-title"> <img src="<%= @user.avatar.url%>" class="img-rounded post-image"> <h4 id="post-name"><%= @user.first_name + ' ' [email protected]_name %> </h4> <div id="post-date"><%= post.created_at.strftime('%d %b -...

Rails - Simple Form - Nested Resources paths

ruby-on-rails,simple-form,simple-form-for
I am trying to make an app in Rails 4 using simple form. I have 3 models: Project, Project_Question, Project_Answer The associations are: Project: has_many :project_questions, dependent: :destroy#, through: :projects accepts_nested_attributes_for :project_questions Project Question: belongs_to :project#, counter_cache: true has_one :project_answer, dependent: :destroy belongs_to :user accepts_nested_attributes_for :project_answer Project Answer: belongs_to :project_question#,...

Ruby if else statement one line not working

ruby-on-rails,ruby,ruby-on-rails-4
I have the following properly working line in a view that adds a class depending on the current_page of the user: <li class="hvr-bottom <%= 'active' if current_page?(root_path) %>"> <%= link_to "Home", root_path %> </li> Now I would also like to add a different class for the else situation, and I...

Routes work in Development But not in Production

ruby-on-rails,routes
Weird Error. I have some routes that work perfectly during development but once i deploy and try to access them it comes up with page does not Exist error I have the following routes.rb file: TransportUnl::Application.routes.draw do resources :trucks resources :shipments do collection do get :autocomplete_location_cs end end devise_for :users...

How to send a mail by postfix mail server with rails?

ruby-on-rails,email,mailer
On my local host, I followed this article made a mail server and it works well. https://www.digitalocean.com/community/tutorials/how-to-install-postfix-on-centos-6 I want to develop a mailer feature with rails framework. Here are my settings: # mailer config.action_mailer.default_url_options = { :host => 'example.com' } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'localhost', port: 25,...

autocomplete rails routes issues

jquery,ruby-on-rails,autocomplete
I'm using the rails-jquery-autocomplete gem for an rfq model to search customers. The autocomplete search works fine when I'm creating a new rfq, but I get this error when I try to use the search while editing a record. ActionController::RoutingError (No route matches [GET] "/rfqs/1/autocomplete_customer_name"): I know what the error...

Host app and engine with same model name, rendering host app's model from inside engine using host app's partial, rails

ruby-on-rails,ruby,rails-engines
I have a host app unicorn with the model Article. I also have a mountable engine hooked into the host app called blorgh. It also has a model: Article. It is namespaced, so the table name for the engine's Article is actually blorgh_articles. What I am trying to do is...

adding background image in style rails 4

ruby-on-rails,twitter-bootstrap,ruby-on-rails-4,asset-pipeline
I am trying to add background image on my web page, it was working when I was using plane html, but now I am integrating it to my rails application. I am using this code to embed the image in my rails application <div class="jumbotron" style="background-image: "url(image-url('lines3.png')"; background-repeat: repeat-x; background-position:...

How to add link_to under Div on ActiveAdmin's show page | Rails 4

ruby-on-rails,ruby,activeadmin,show
I have implemented one panel of Active Admin's show page. In this panel I am showing list of data by loop. Here is what I did: show do default_main_content panel "Best #{trip_type.camelize} (Live)" do live_datas1.each do |live| div do live["outbound_date"].strftime('%A')+ ", " + live["outbound_date"].strftime('%Y-%m-%d') + " To " + live["inbound_date"].strftime('%A')...

How do I setup a multi-option voting system using acts-as-votable?

ruby-on-rails,ruby-on-rails-4
I want to use acts-as-votable to implement a voting system where I can supply multiple custom options - e.g. 5 buttons ('blue', 'red', 'green', 'grey', 'white'). I want my users to be able to choose only 1 of those colors, but I would like to be able to tally up...

Not able to create staging instance on heroku [duplicate]

ruby-on-rails,git,heroku,sqlite3
This question already has an answer here: Errors of pushing rails app to Heroku error occurred while installing sqlite3, and Bundler cannot continue 3 answers I am trying to create a staging instance of my app on heroku. While I am doing git push staging master I am getting...

unable to retrieve data from a form in rails

ruby-on-rails
i am trying to access the data from a form. <% form_tag(:action => "test") do %> <p> Name: <%= text_field_tag("name","web programmer") %> </p> <%= submit_tag ("Save data") %> <% end %> this form is in views/challenges/show.html I have written this piece of code in challenges_controller def test @name = params[:name]...

Allowing some enabled and disabled option on collection_select

ruby-on-rails,ruby
I am trying to populate a dropdown box on a view that has all the states. This works just fine: <%= f.collection_select :state_id, @states, :id, :name %> Now, I need to make the following: Some states are going to be disabled for choosing, but they still have to appear on...

If statement for search field in Rails

jquery,ruby-on-rails,search,if-statement
I have a blog site and recently added a search bar for visitors to browse through blog posts. When used, all of the posts go away in the directory and only those which return via the search appear. In order to show the general directory and view all, I would...

Getting a collection via Ajax to show in view

jquery,ruby-on-rails,ajax
All I'm trying to do is have a collection populate in the view when a user clicks a button. But I feel like I'm making this way too complicated and it's not working. See my code - where am I going wrong? Click handler: $('#filterrific_results').find('.followup-injury').on('click', function(e){ e.preventDefault(); $.ajax({ url: "/assessments/followups",...

Saving to a database using a Nokogiri (json?) rake task

ruby-on-rails,ruby,json,nokogiri
RoR noob here! I have a rake task doing what I want to do I am just stuck on how to get the results saved to my language table. I want the results from this rake task to populate the values of the language field on my language table. I'm...

Rails: get f.range_field to submit null or nil as default value

ruby-on-rails,forms
In my app, I have a range_field where a user can select 0..100. But if they don't select anything, I want the form to submit "null" or nil as the value rather than a numerical value. Is this possible? If I use the below syntax, then everything works except value...

Rails basic auth not working properly

ruby-on-rails,ruby,authentication
I am building a small API that uses basic authentication. What I have done, is that a user can generate a username and password, that could be used to authenticate to the API. However I have discovered that it is not working 100% as intended. It appears that a request...

How to pass array in rails 4 strong parameters

ruby-on-rails,arrays
I have to pass a array of food_item_ids in my order_controller. Every order will have many food_items. How can I pass these food_items_id as an array in strong parameters. orders_controller.rb def create @order = Order.new(order_params) if @order.save render :json, @order, status:201, location: [:api, @order] else render :json, { errors: @order.errors...

Seeding fails validation for nested tables (validates_presence_of)

ruby-on-rails,ruby,validation,ruby-on-rails-4,associations
An Organization model has a 1:many association with a User model. I have the following validation in my User model file: belongs_to :organization validates_presence_of :organization_id, :unless => 'usertype==1' If usertype is 1, it means the user will have no organization associated to it. For a different usertype the presence of...

rails - NameError (undefined local variable or method while using has_many :through

ruby-on-rails,ruby,ruby-on-rails-4
My rails app gives following error: NameError (undefined local variable or method 'fac_allocs' for #): app/models/room.rb:4:in '' app/models/room.rb:1:in '' app/controllers/rooms_controller.rb:3:in 'index' room.rb file class Room < ActiveRecord::Base has_many :bookings has_many :fac_allocs has_many :facs, :through => fac_allocs end ...

Slimming down polymorphic controller; where does the logic belong?

ruby-on-rails,polymorphism
I am implementing my own RESTful voting system. 'Questions' and 'Answers' are both votable. Votes are created, updated and deleted. When an action is preformed on a voteable, the voteable's class is passed as a param. The controller needs to look at the votable_type to retrieve the correct votable object...

Error installing gem twitter on Ubuntu 15.04

ruby-on-rails,ruby,ubuntu,twitter
Am trying to install twitter gem on Ubuntu 15.04 and this error keeps popping up gem install twitter Building native extensions. This could take a while... ERROR: Error installing twitter: ERROR: Failed to build gem native extension. /usr/bin/ruby2.1 extconf.rb mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h extconf failed,...

Rails - link_to path based on object's name + refactoring multiple custom actions

ruby-on-rails,ruby,refactoring
I'm looking to simplify the link_to path based on thr object's name and also am looking into refactoring multiple custom actions. I've managed to get this working below. <% ServiceMenu.all.each do |menu| %> <tr class=" <%= cycle('odd', 'even') %>"> <td><%= link_to menu.name, ("tech/""#{menu.name.parameterize}") %></td> </tr> <% end %> I feel...

how to define extra method for rails form text_field

ruby-on-rails,ruby
After removing dimensions from my table, my scaffolded view hit this error: undefined method 'dimensions' for this code: <div class="field"> <%= f.label :dimensions %><br> <%= f.text_field :dimensions %> </div> I want to keep this dimention field in the form and in the controller I want to split this string into...

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"...

Mongoid HABTM relationships across embedded documents

ruby-on-rails,ruby-on-rails-4,mongoid,embedded-documents
I'm trying to create a Mongoid N-N reference association between two embedded documents in Rails 4 however I'm finding it difficult to get my head round how this is done. I started by adding the HABTM association to the relevant models below (Track and Option) but of course I'm getting...

Rails 4 + delayed job - constantly writing debug code to production logs

ruby-on-rails,debugging,delayed-job
I'm using delayed job for the first time, and it seems to be working fine. I started to tail my production log to fix another issue, and found that delayed job is constantly updating the production log with debug code. Is this normal, and can I turn it off? [2015-06-14T16:05:35.983383...

Migrate from existing password_digest column?

ruby-on-rails,ruby-on-rails-4,devise,bcrypt
I have a custom User model with lots of rows. I have a password_digest column that I want to keep. (it comes from has_secure_password) And I also want to use Devise database authenticatable, but from my limited knowledge on Devise, I have to use the encrypted_password column. Is there a...

What is Rack::Utils.multipart_part_limit within Rails and what function does it perform?

ruby-on-rails,ruby,rack,multipart
Rack::Utils.multipart_part_limit is set to 128 by default. What purpose does the value have and what effect does it have within the Rails system?...

Make instance variable accessible through hash in Ruby

ruby-on-rails,ruby,ruby-on-rails-4,activerecord
In Rails, ActiveRecord objects, attributes are accessible via method as well as through Hash. Example: user = User.first # Assuming User to be inheriting from ActiveRecord::Base user.name # Accessing attribute 'name' via method user[:name] # Attribute 'name' is accessible via hash as well How to make instance variables accessible through...

Ruby API Call Page Issue

ruby-on-rails,ruby,json,api,httparty
This might be a basic issue but very common so it might be helpful to other people in the future. I use HTTParty to make a get request to an API, which returns some information, something like this: { datapath: "blah-blah.blah.blah", success: true, info: { row_limit: 500, total_results: 2700, total_pages:...

Ruby: How to copy the multidimensional array in new array?

ruby-on-rails,arrays,ruby,multidimensional-array
seating_arrangement [ [:first, :second, :none], [:first, :none, :second], [:second, :second, :first], ] I need to copy this array into new array. I tried to do it by following code: class Simulator @@current_state def initialize(seating_arrangement) @@current_state = seating_arrangement.dup end But whenever I am making any changes to seating_arrangement current_state changes automatically....

Rails Generates Blank Record Even Input Data

ruby-on-rails,crud
I am learning to use CRUD, and setup a page to add a record, however it only generated blank record? Can you take a look my code? thanks! here is the Page controller: class PagesController < ApplicationController def index @test = Page.all end def new @test = Page.new end def...

Rails, DNSimple, Heroku and SSL - do I need a certificate?

ruby-on-rails,ssl,heroku,dnsimple
So I'm currently deploying my app via Heroku. I noticed that in my-app-name.herokuapp.com has HTTPS, so if I do config.force_ssl = true in my environments/production.rb it seems like I have wildcare SSL, right? Now I'm using DNSimple to get my actual name - call it my-app-name.com. Which currently resolves to...

RoR send email with html template

ruby-on-rails,html-email
I would like send email with html.erb template and I have some code. Like this: class Mailer < ActionMailer::Base def notification(to_email) begin mail(to: '[email protected]', subject: "Test message") rescue Exception => e return end end end And some html.erb file: Hello, <%= @name %>. But I don't know how to attach...

On rendering from controller, current_page method does not seem to work

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller
I have a navigation bar included in application.html.erb. Because for some pages, such as the signup page, I need to place additional code inside the navigation bar, I have excluded those pages for showing the navigation bar through application.html.erb and instead included it in their respective view pages. See code...

Order parent model using children in rails

ruby-on-rails,order,models
I have model product and vote, I need to order products by votes count DESC. product has_many :votes, vote belongs_to :product index_controller.rb def index @products = Product.all end ...

User.id not getting saved in form

ruby-on-rails
I have 2 models, promos and users. Promo belongs_to :user User has_many :promos In my routing, I have nested resources: devise_for :users resources :users do resources :promos end I have a form to create new promos, with simpleform <%= simple_form_for [current_user, @promo] do |f| %> <%= f.input :title, label: "Título...

Rails, default.js is empty, and jquery and jquery_ujs not loaded

jquery,ruby-on-rails,ruby,ruby-on-rails-4,rubygems
I am practicing ruby on rails by using rails guides. In the section 5.13 Deleting Articles they are showing how to create the delete (destroy) functionality. I followed the steps correctly, but the delete confirmation dialogue isn't shown and the articles are not getting deleted. When I checked the chrome...

Rendering a dynamically generated background based on width

html,css,ruby-on-rails,sass,haml
So I have a background image attribute (as a string referencing an image in the project), that belongs to a Badge table. I'm rendering each background image based on the current path. But I want to render different images at two different max-widths. For example, .badge-headline-background{style: "background-image:url(../assets/header-graphics/#{@badge.background})"} renders a background...

Call method to generate arguments in ruby works in 1.8.7 but not 1.9.3

ruby-on-rails,ruby,ruby-1.9.3
This is something that I had working in ruby 1.8.7, but no longer works in 1.9.3, and I am not sure what changes make this fail. Previously, I had something like this myFunction(submitArgs()) where submitArgs was a helper method that could be called with some options def submitArgs(args={}) #Some logic/manipulations...

No onclick event for jQuery element added after initial page load

jquery,ruby-on-rails,nested-forms
In our rails app, we have a table where each tbody row is a nested field. I want to limit nested fields based on current field count. To do so, I am following this guide provided by the nested_form docs. To better suit our app, I modified the code below....

Styling navbar: interaction between different styling settings

html,css,ruby-on-rails,ruby-on-rails-4
I'm having problems with styling my navigation bar, specifally the drop-down menu within the navigation bar. The two li elements below (the ones linking to "Profile" and "Edit profile" don't show up right. As you can see I have added the class my-dropdown-item in two different manners, both with the...

Controller method: Contact form should render different page depending on where the form is used

ruby-on-rails,ruby,forms,ruby-on-rails-4,controller
I have a contact form on a special page dedicated to this form. The dedicated controller includes: def new @message = Message.new end def create @message = Message.new(message_params) if @message.valid? MessageMailer.new_message(@message).deliver_now flash[:success] = "Thank you!" redirect_to contact_path else render 'new' end end Now I would also like to include this...

User path with username

ruby-on-rails,ruby,path,user,friendly-id
To show User's profile I used their id. In controller: @user = User.find(params[:id]) In routes: get ':id' => 'users#show' But now I try new way with username: get ':username' => 'users#show' #route @user = User.find_by(username: params[:username]) #controller And when I go to user's profile with /username I see error: undefined...