Menu
  • HOME
  • TAGS

Stack level too deep because recursion

ruby-on-rails,ruby,ruby-on-rails-4,twitter

If you express the relation properly, ActiveRecord will do it for you class Tweet belongs_to :original_tweet, class_name: Tweet has_many :retweets, class_name: Tweet, dependent: :destroy, inverse_of :original_tweet end Tweet.last.destroy # will now destroy dependents ...

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

ruby-on-rails,ruby

You can try : dateLabels = <%= raw @mapped_dates.as_json %>; This will return ["Jan 1", "Jan 2", "Jan 3", ... ] For ActiveSupport::TimeWithZone problem, please do - In config/initializers/time_zone.rb class ActiveSupport::TimeWithZone def as_json(options = {}) if ActiveSupport::JSON::Encoding.use_standard_json_time_format xmlschema else %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) end end end ...

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

ruby-on-rails,validation,activerecord

You can use =~ operator instead to match a string with regex, using this you can add a condition in setter methods def resolution=(res) if res =~ /\A\d+x{1}\d+\d/ # do something else # errors.add(...) end end but, as you have already used attr_accessor, you don't have to define getter and...

adding background image in style rails 4

ruby-on-rails,twitter-bootstrap,ruby-on-rails-4,asset-pipeline

You should change "background-image:"url(image-url('lines3.png')"; into "background-image:"image-url(image-url('lines3.png')"; http://guides.rubyonrails.org/asset_pipeline.html#css-and-sass Or you can try with: background-image: url(<%= asset_path 'lines3.png' %>)...

User path with username

ruby-on-rails,ruby,path,user,friendly-id

Artyom you can use the friendly-id gem if you want to make this process easier on you. Ryan Bates has a Railscast on it as well. That way you can use strings as ids (i.e. your username) in the url: http://localhost:3000/articles/hello-world Let me know if you have any questions, -Dave...

How to exclude guest users from getting emailed Rails 4 Devise

ruby-on-rails,email,ruby-on-rails-4,devise,mailer

def welcome_email(user) # The following line is unnecessary. Normally, you do # something like this when you want to make a variable # available to a view #@user = user # You can make the if more explicit by writing # if user.id == nil, but if will return false...

how to get validated the associated attributes? rails4

ruby-on-rails,validation

Use valid? method. It will trigger validations defined in model and return true or false. if @man.valid? @man.save else #do smth else Further reading: http://guides.rubyonrails.org/active_record_validations.html#valid-questionmark-and-invalid-questionmark...

Rails Association Guidance [on hold]

ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2

So, the complex part of your situation is that you have one thing (Surgery) that can be of many different types, and the different types have different fields. There are a number of different approaches to this problem, and I don't believe there's wide consensus on the 'best way'. The...

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

jquery,ruby-on-rails,ruby,ruby-on-rails-4,rubygems

Everything is OK from your side. You said that you're on Windows 7, I also experienced this problem once when I needed to run rails on windows for some reason. Than I found an answer here which helped me to get out of this problem. Actually coffee-script-source, v 1.9.x gives...

Rails - searching in the console

ruby-on-rails,rails-console

One way I believe you could accomplish this is first finding the scope by project_id and then from there get the background of that scope (since a scope has one background): scope = Scope.where(:project_id => 95).take background = scope.background You could potentially chain them together: Scope.where(:project_id => 95).take.background (Note, haven't...

Rspec view test with url parameters

ruby-on-rails,unit-testing,testing,rspec,rspec-rails

Because these are redirects, controller testing with render_views will not work. Nope, you are just doing it wrong. If StaticpagesController#dashboard accepts url parameters you should test how it responds to said parameters in the controller spec for StaticpagesController. RSpec.describe StaticpagesController, type: :controller do describe 'GET #dashboard' do render_views it...

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

ruby-on-rails,forms

You can just add a hidden checkbox value to judge whether user select or not. = f.range_field :content, :value=> nil, :class=> "question-field percentage", :step => 10, :in => 0..101, :data => {:question => question.id = check_box_tag :range_clicked, true, false, style:'display:none;' and then add a js function to tell whether user...

Error when trying to install app with mysql2 gem

mysql,ruby-on-rails,ruby,ruby-on-rails-4

The error log says: ld: library not found for -lssl So, you need to install libssl: brew install openssl Hope it helps....

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

ruby-on-rails,gem,activeadmin

Add the following to your Polls Controller- def new @poll = Poll.new 4.times do @poll.answers.build end end ...

Sortable in Rails 4

ruby-on-rails,jquery-ui,ruby-on-rails-4

In case anyone is wondering, this is what worked for me in Rails 4: def sort params[:video].each_with_index do |id, index| Video.update(id, position: index+1) end render :queue end ...

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

ruby-on-rails,ruby

Use ::Article to refer to the top-level namespace class, and MyEngine::Article to refer to the engine's class. While using Article alone within the MyEngine namespace will resolve correctly, doing this introduces a couple of pitfalls: It makes it confusing to understand your code as there are multiple references to an...

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

ruby-on-rails,nested-forms

The trick is to use fields_for. It gives you a "scoped" form builder instance which creates inputs for the nested fields. = form_for (:post) do |f| # ... a bunch of fields = f.fields_for :images do |builder| = builder.label :is_on, "Set as primary" = builder.check_box :is_on However your solution has...

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

ruby-on-rails,ruby,ruby-on-rails-4

In your associations instead of fac_allocs you need to use a symbol because rails is looking a variable or method named fac_allocs instead of your associated model has_many :facs, through: :fac_allocs ...

Rails shared controller actions

ruby-on-rails,ruby,ruby-on-rails-4

You should pass actions to the included block and perform_search_on to the class_methods block. module Searchable extend ActiveSupport::Concern class_methods do def perform_search_on(klass, associations = {}) ............. end end included do def filter respond_to do |format| format.json { render 'api/search/filters.json' } end end end end When your Searchable module include a...

autocomplete rails routes issues

jquery,ruby-on-rails,autocomplete

You need a member route for this to work (since you are trying to access "/rfqs/1/autocomplete_customer_name"): get :autocomplete_customer_name, :on => :member Member routes add an :id param in the route, while the collection routes work without id params: resources :items do get :foo, on: :member get :bar, on: :collection end...

Javascript not executing when using link_to

javascript,jquery,ruby-on-rails

This is a result of Turbolinks. You can get around this with the following: $(document).on 'click', '.my-btn', (event) -> ... This is happening because Turbolinks is loading the page, and there isn't a document ready event being fired. You want to wait until Turbolinks fires the page:load event. You do...

Ruby on Rails - Help Adding Badges to Application

ruby-on-rails,ruby,rest,activerecord,one-to-many

Take a look at merit gem. Even if you want to develop your own badge system from scratch this gem contains plenty of nice solutions you can use. https://github.com/merit-gem/merit

Showing and editing has_many objects in Rails

ruby-on-rails,ruby-on-rails-4

Since you need to support both (POST /milestones and POST /projects/:project_id/milestones) the project_id to the form: <%= form_for [@project,Milestone.new] do |f| %> ... <%= f.hidden_field(:project_id, value: @project_id) %> ... <%- end -%> Or if your resource is always nested than project_id available in the params in your controller so you...

Rails less url path change

ruby-on-rails,ruby,url,path,less

You should use the font_url, and put the font in app/assets/fonts @font-face { font-family: 'SomeFont'; src: font_url("db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); //... } ...

Routes work in Development But not in Production

ruby-on-rails,routes

As you can see from logs, you got error page because of line 78 of app/views/shared/_header.html.erb file. In this piece of code, where you creating link <%= link_to "My Account", edit_company_path(current_user.company_id) %> Check if company_id is not nil for that particular user. I'm pretty sure it's nil in your case....

Elasticsearch advanced search

ruby-on-rails,ruby,search

I will prefer to do this in your action. tags = params[:q].present? ? params[:q].scan(/#[^ #]+/).collect{|tag| tag.gsub(/#/, '')} : [] now you can use this array of tags in search function...

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

jquery,html,ruby-on-rails

You need to use event delegation jquery .on() $(document).on('click', '.remove', function() { $(this).closest('.row').remove(); return false; }); ...

Sorting in Ruby on rails

ruby-on-rails,json,sorting

You're not getting the results you want because you're not assigning the sorted user_infos back into the user_infos variable. You can do the following: user_infos = user_infos.sort {|a, b| - (a['can_go'] <=> b['can_go']) } # -or- user_infos.sort! {|a, b| - (a['can_go'] <=> b['can_go']) } The first version of sort creates...

whenever gem not working, Rails 4

ruby-on-rails,ruby,ruby-on-rails-3,cron,whenever

PATH problem may be, by putting the following at the top of the schedule.rb, ensure correct bundle path env :PATH, ENV['PATH'] Or try to add following if above one not work. env :GEM_PATH, ENV['GEM_PATH'] ...

Make instance variable accessible through hash in Ruby

ruby-on-rails,ruby,ruby-on-rails-4,activerecord

It's not "through Hash", it's "array access" operator. To implement it, you need to define methods: def [](*keys) # Define here end def []=(*keys, value) # Define here end Of course, if you won't be using multiple keys to access an element, you're fine with using just key instead of...

No onclick event for jQuery element added after initial page load

jquery,ruby-on-rails,nested-forms

Try replacing $('<selector>').click(function() { with $(document).delegate('<selector>', 'click', function() { this should be triggered on elements that were added after this script was run initially. Explanation: When you do .click you are adding events on to a known, specific, list of elements. If you add new elements they don't have the...

User.id not getting saved in form

ruby-on-rails

When you are using nested routes you need to get the parent id from the parameters and merge it with the form parameters. When you post the form the parameters look something like this: { user_id: 1, promo: { title: "¡Ay, caramba!" } } Doing params.require(:promo)... slices the params hash...

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

Change required (in github notation): - myFunction(submitArgs()) + myFunction(*submitArgs) The reason that [I assume] myFunction is declared taking two arguments: def myFunction a1, a2 Hence the array must be splatted before passing to it. I wonder how that worked in 1.8....

Couldn't find User with 'id'=show

ruby-on-rails,ruby,devise

The show action depends on looking up an id. Since you're hitting the URL /users/show, it assumes you're trying to look up a user with id of show. Instead, you should be going to a url like /users/1 to trigger the show action. The Rails guide on routing has a...

rendering the partials in controller after the validation check

ruby-on-rails,ruby-on-rails-4,model-view-controller

Why this is not working? if params[:user][:user_role] render :partial => 'users/mentor' else render :partial => 'users/mentee' end params[:user][:user_role] is nil. You can check it using lots of way: Above your if condition raise params[:user].inspect Why its nil? Reason of this is You are passing new_user_path(user_role: true) user_role true, but user_role...

Slimming down polymorphic controller; where does the logic belong?

ruby-on-rails,polymorphism

@vote = Vote.find(:id) #it depends of what is your params[:vote] @votable = @vote.votable # it will return parent of your vote http://guides.rubyonrails.org/association_basics.html#polymorphic-associations You can wrap above code in a private method and then use it in you actions, i.e: .... def update votable.update(...) end private def votable @votable ||= Vote.find(:id).votable...

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

ruby-on-rails,activerecord,callback

It'll work without any issue, as Active Record wraps-up these callback methods in a single transaction. Since the object is destroyed in first yield, it seems the later is not feasible (assuming everything is running in one thread). How Rails handles this? No, object isn't destroyed in first yield. Object...

Rails Generates Blank Record Even Input Data

ruby-on-rails,crud

Strong parameters Rails sends form parameters in nested hashes. { page: { subject_id: 1, name: 'Hello World.' } } So to whitelist the parameters you would do. class PagesController < ApplicationController def index @test = Page.all end def new @test = Page.new end def create @test = Page.new(page_params) if @test.save...

Not able to create staging instance on heroku [duplicate]

ruby-on-rails,git,heroku,sqlite3

In your Gemfile group :production do gem 'pg', '0.17.1' gem 'rails_12factor', '0.0.2’ end and also remove gem 'sqlite3' OR group :development, :test do gem 'sqlite3' end Because heroku can't install the sqlite3 gem. But you can tell bundler that it shouldn't be trying to except when developing. Then run bundle...

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

ruby-on-rails,ruby,json,nokogiri

namespace :scraper do desc "Scraper" task scrape: :environment do require 'open-uri' require 'nokogiri' require 'csv' require 'json' url = "https://en.wikipedia.org/wiki/List_of_languages_by_number_of_native_speakers" page = Nokogiri::HTML(open(url)) page.css('td b a').each do |line| puts line.text # "Spanish" Language.create(language: line.text) end end end ...

Active Record Where Clause For Relation In Model

ruby-on-rails,activerecord

I want to select sites of premium user This will do User.includes(:sites).where('users.category = ?', 'premium') Update If sites also have categories like 'wordpress or joomla', how do i apply where clause to select only wordpress sites of premium users For that you need to tweak the query like this...

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

ruby-on-rails,integration-testing

If you look at the error First argument in form cannot contain nil or be empty You can clearly make out from it that the first argument that's @micropost variable is nil. Now move to the controller and see if you have set that variable or not. In else part...

Rails basic auth not working properly

ruby-on-rails,ruby,authentication

@user.keys.each do |key| username == key.api_id && password == key.api_key end This piece of code returns a value of .each, which is the collection it's called on (@user.keys in this case). As it is a truthy value, the check will pass always, regardless of what are the results of evaluating...

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

ruby-on-rails,ruby,rack,multipart

Telling it short, this value limits the amount of simultaneously opened files for multipart requests. To understand better what is multipart, you can see this question. The reason for this limitation is an ability to better adjust your app for your server. If you have too many files opened at...

Undefined local variable post

ruby-on-rails,ruby,variables,undefined,local

You need to use partial: when you pass locals to a partial as follows: <%= render partial: 'post', locals: { post: post, user: @user} %> I hope this will help you....

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

ruby-on-rails,activerecord

As I said, you need to tweak your create action like this in order to save group_id. def create @group = Group.find(params[:group_id]) @discussion = current_user.discussions.build(discussion_params) @discussion.group_id = @group.id if @discussion.save flash[:success] = "Discussion started." redirect_to root_url end end OR You can add a hidden_field in your form_for to save group_id...

Ruby API Call Page Issue

ruby-on-rails,ruby,json,api,httparty

In fact, a quick google led me to this page https://app.enigma.io/api#data which tells me the parameter in question is limit, and that the max is 500. So, it looks like you can't get the data for all rows in one hit. If you really NEED the data for all the...

Rails, Simple Form, Nested Forms

ruby-on-rails,simple-form

You should change this line <% f.simple_fields_for :project_questions do |f| %> to this <%= simple_form_for :project_questions do |f| %> in order to make it work.

RSpec test for rake task

ruby-on-rails,ruby,rspec,rake-task

A couple things. First off, you should put created_at in the create method: user.items.create(description: "Old Item", created_at: 12.days.ago). Second, you need to call user.reload in order for the changes from your rake task to be available. So it should look like this: user.reload expect(user.items.count).to eq 1 etc...

Getting a collection via Ajax to show in view

jquery,ruby-on-rails,ajax

Your partial (currently named: _followup.html.erb in your example) should just be the code to produce a single row, Rails will iterate over it for you, and you should name it after the model it represents, ie. # app/views/assessments/_assessment.html.erb <%= assessment.name %> Then in your app/views/assessments/followups.html.erb view you'd use that partial...

Seeding fails validation for nested tables (validates_presence_of)

ruby-on-rails,ruby,validation,ruby-on-rails-4,associations

Found this : Validating nested association in Rails (last chapter) class User belongs_to :organization, inverse_of: :users validates_presence_of :organization_id, :unless => 'usertype==1' end class Organization has_many :users accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true end The documentation is not quite clear about it but I think it's worth a try....

Rails 4 - Javascript - trouble with .not()

javascript,jquery,html,ruby-on-rails,ruby-on-rails-4

jquery's not function will return a jquery object, not an integer. I can't validate if the rest of your logic is working but if you want to get the number of DOM elements that matches your jquery element, you should do it using the length value: if ($('PP').not('.closed').length>=2) { window.alert('already...

Active Record association links, but can't assign values

ruby-on-rails

Your column should be permission_id, not permissions_id. That is why AR doesn't find the related model.

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

ruby-on-rails,ssl,heroku,dnsimple

I just went through this same scenario. The certificate you see in your herokuapp is the wildcard certificate issued for *.herokuapp.com. If you want to secure a custom domain name http://my-app-name.com, you would need to purchase and install your own wildcard certificate via DNSimple. ...

unable to retrieve data from a form in rails

ruby-on-rails

You need to display your form so instead of using <% %> you need to use <%= %>, checkout this answer for differences between them. By default forms use POST verb and you have defined a route for GET request. Change your form to this: <%= form_tag({action: :test}, {method: :get})...

Can Rails deal with DB uniqueness without index?

mysql,ruby-on-rails,rdbms

Because there is no need for other ways. Under the hood it's all the same: when you define a UNIQUE constraint, a UNIQUE index is created on that table to enforce it. Question from DBA.SE: When should I use a unique constraint instead of a unique index? So for a...

Javascript Changing Random Background Image Issue

javascript,html,ruby-on-rails,ruby-on-rails-4,background-image

I don't really want to get deep into your code, in two words: whatever is happening is happening because you have to wait for some actions to complete before they complete (such as animations) and you never want have timeouts within intervals. This has to be helpful: var images =...

RoR send email with html template

ruby-on-rails,html-email

You can create a page named notification.html.erb in app/views/mailer directory. You will get all instance variable in notification.html.erb that is defined in your def notification(to_email) def notification(to_email) @name = #pass name here #your code goes here end Now @name will be available in notification.html.erb like Hello, <%= @name %> ...

Migrate from existing password_digest column?

ruby-on-rails,ruby-on-rails-4,devise,bcrypt

Simply write a migration to rename the column name, it will not loose your data. rails g migration ChangeColumnName this will generate a migration file class ChangeColumnName < ActiveRecord::Migration def change rename_column :users, :password_digest, :encrypted_password end end ...

Ruby if else statement one line not working

ruby-on-rails,ruby,ruby-on-rails-4

You do not need to use "if" in the ternary. Change your statement to look like this: <%= current_page?(root_path) ? 'active' : 'inactive' %> ...

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

ruby-on-rails,email,mailer

You need to change the delivery_method from :smtp to :sendmail config.action_mailer.delivery_method = :sendmail ...

rails Initialize new object through associated search

ruby-on-rails

Scanning your code quickly, I don't see anything missing and while there's a number of ways to get this done, I think you're on the (a) right track. Building things like this in Rails involves getting quite a number of components all working together at the same time, so in...

Error installing gem twitter on Ubuntu 15.04

ruby-on-rails,ruby,ubuntu,twitter

You are getting this error because there is no ruby development environment installed. Development environment is needed to compile ruby extensions, You should install development first using command below: $ sudo apt-get install ruby-dev ...

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

ruby-on-rails

If you're using Rails 4 you can do: @user = User.find_by(first_name: "John", last_name: "Doe") If rails 3: @user = User.find_by_first_name_and_last_name("John", "Doe")...

If statement for search field in Rails

jquery,ruby-on-rails,search,if-statement

The standard way to use a search would be to include a parameter in the URL. That way you can have a similar to if user_signed_in? check for the parameter: if params[:search].present?.

CSS placing image by a form

html,css,ruby-on-rails,zurb-foundation-5

The CSS display:inline is being applied on the container, not on it's elements. One approach is to just float the <img> using class=left and move it alongside the <form>, inside the centered div. <div class="small-9 large-centered columns"> <%= image_tag("successful_forex_trader.jpg", :class => 'left', :alt => "Forex Money Manager") %> <%= form_for(@investor)...

Mongoid HABTM relationships across embedded documents

ruby-on-rails,ruby-on-rails-4,mongoid,embedded-documents

The reason you are getting the error is because of the logic below. If you are going to need to represent many-to-many relations, do not use a document model to store your state. Use a relational one === You can't represent a many to many relation without an association/reference table/object....

Rails4 + sunspot search

mysql,ruby-on-rails,solr,sunspot

How are you accessing the result? If you are calling .results method then it will fire db query. You should iterate over hits and get the require field to avoid db query.

How to convert a string into datetime format using rails?

ruby-on-rails

DateTime.parse('2015-06-20 15:15:15') ...

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

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller

You can use content_for and yields to create a default in your layout which views can override. # layouts/application.html.erb: <% if content_for?(:banner) %> <%= yield(:banner) %> <% else %> <div id="banner"> <h1>This is the default...</h1> </div> <% end %> /users/signup.html.erb: <%- content_for :banner, flush: true do -%> <!-- move along,...

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

ruby-on-rails,ruby-on-rails-4,heroku,dns

I discovered the answer. I am on Cloudflare's network. Turns out that if on their "Crypto" panel, if the SSL is set to "flexible" then you will get the redirect loop error. Had to set it to "Full".

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

ruby-on-rails,debugging,delayed-job

It is normal, you must have set log_level in config/environments/production.rb to :debug. Changing it to :info will not update production log with delayed job's debug comments....

Heroku rake db:migrate failing - uninitialized constant

ruby-on-rails,ruby,heroku

Your migration file named should correspond to AddWeightToExercises. It should be accordingly xxxxxxxx_add_weight_to_exercises, where xxxxxxx corresponds to a particular timestamp.

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

Grab the host's articles from the engine: @host_app_articles = ::Article.all #refers to top-level namespace class Render it from the view inside the engine: <% @host_articles.each do |article| %> <%= render file: "/app/views/articles/_article", locals: {article: article} %> <% end %> And just for completion, here is what the partial might look...

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

ruby-on-rails,ruby,refactoring

You can change your routes : resources :techs, :only => [:index, :show], shallow: true do resources :cars, only: [:new, :create] collection do get 'part/:part_name' => "techs#part", as: :part end end Then add the action : def part @techs = Tech.joins(:services).where(services: { name: params[:part_name]}) end and the view will be :...

Rails - Simple Form - Nested Resources paths

ruby-on-rails,simple-form,simple-form-for

Your new action of project_answers controller should be having @project, @project_question defined def new @project_answer = ProjectAnswer.new @project = Project.find(params[:project_id]) @project_question = ProjectQuestion.find(params[:project_question_id]) end So that you can use those in the form like this <%= simple_form_for [@project, @project_question, @project_answer] do |f| %> ...

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

You can use something called action_name in Rails 4. action_name gives you the name of the action your view got fired from. Now you can send this property to the method create through a hidden field like following: <%= hidden_field_tag "action_name", action_name %> This line of code will send params[:action_name]...

Order parent model using children in rails

ruby-on-rails,order,models

@products = Product.order("count(votes) DESC") If you have not votes column then use: @products = Product.all.sort { |a, b| b.votes.count <=> a.votes.count } ...

Styling navbar: interaction between different styling settings

html,css,ruby-on-rails,ruby-on-rails-4

Add override class in the link_to: <%= link_to "Edit profile", edit_user_path(current_user), class:"my-dropdown-item" %> Add to CSS .my-dropdown-item { a { width: 100%; color: #000 !important; } } This might need some tweaking, let me know....

Redirect if ActiveRecord::RecordNotUnique error exists

ruby-on-rails,postgresql,activerecord,error-handling

Just the way you catch every other error begin Transaction.create!(:status => params[:st], :transaction_id => params[:tx], :purchased_at => Time.now) rescue ActiveRecord::RecordNotUnique redirect_to root_path end ...

How to pass array in rails 4 strong parameters

ruby-on-rails,arrays

According to the docs https://github.com/rails/strong_parameters#permitted-scalar-values: The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile. To declare that the value in params must be an array of permitted scalar values map the key to an empty array: params.permit(:id => []) If...

Same enum values for multiple columns

ruby-on-rails,ruby,enums

Maybe it makes extract the planet as another model? def Planet enum type: %w(earth mars jupiter) end class PlanetEdge < ActiveRecord::Base belongs_to :first_planet, class_name: 'Planet' belongs_to :second_planet, class_name: 'Planet' end You can create a PlanetEdge by using accepts_nested_attributes_for: class PlanetEdge < ActiveRecord::Base belongs_to :first_planet, class_name: 'Planet' belongs_to :second_planet, class_name: 'Planet'...

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

ruby-on-rails,arrays,ruby,multidimensional-array

dup does not create a deep copy, it copies only the outermost object. From that docs: Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. If you are not sure how deep your object...

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

ruby-on-rails,railstutorial.org,minitest,guard

2 tests, 2 assumptions, 0 failures, 0 errors, 0 skips means guard successfully ran 2 tests containing two assumptions (assertions). The messages in the debug log are telling you of missing dependencies. You could save yourself a big headache and use the free cloud 9 and heroku setup Hartl suggests,...

Rendering a dynamically generated background based on width

html,css,ruby-on-rails,sass,haml

This should work, using the dynamic value .badge-headline-background :css .badge-headline-background { background-image: url("../assets/header-graphics/#{@badge.background}"); } @media (max-width: 700px) { .badge-headline-background { background-image: url("../assets/small-header-graphics/#{@badge.background}"); } } ...

Heroku RAM not increasing with upgraded dynos

ruby-on-rails,ruby,ruby-on-rails-3,memory,heroku

That log excert is from a one off dyno, a la heroku run console - this is entirely seperate to your web dynos which you may be runnning 2x dyno's for. You need to specifiy --size=2x in your heroku run command to have the one off process use 2x dynos.

paper clip show image url is undefine

ruby-on-rails

So your @result is a collection of users. Just call <%= r.image.url(:medium) %>

RESTful routing best practice when referencing current_user from route?

ruby-on-rails,rest

I would've added special routes for current user profile actions, in this case you don't have to check anything. Just load and display the data of current user. For example: /my-profile/edit /my-profile/newsfeed It's not that RESTful but you don't have to put extra checks keeping your code clean. If you...

adding link_to with image_tag and image path both

html,ruby-on-rails,image,ruby-on-rails-4,svg

Remove the space after image_tag. <%= link_to '#' do %> My Project <%= image_tag('logo.svg', "data-svg-fallback" => image_path('logo.svg'), :align=> "left" ,:style => "padding-right: 5px;") %> <% end %> ...

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

ruby-on-rails,angularjs,rspec,capybara

My guess is that your create(:fighter) call is running in a different thread (and database transaction) than the AJAX get request. Try adding this snippet to your rails_helper. class ActiveRecord::Base mattr_accessor :shared_connection @@shared_connection = nil def self.connection @@shared_connection || retrieve_connection end end ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection Source: https://github.com/jnicklas/capybara#transactions-and-database-setup...

Allowing some enabled and disabled option on collection_select

ruby-on-rails,ruby

collection_select internally relies on options_from_collection_for_select helper. Rather than using the collection_select directly, you can use select and pass the result of a options_from_collection_for_select call. The reason you may want to call options_from_collection_for_select directly, is because this method also accepts an optional selected parameter that could be used to pass a...

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

ruby-on-rails,ruby

Don't know what the surrounding code looks like so let's assume your code is the entire body of a method. Then a guard clause might look like this: def some_method return if params[:"available_#{district.id}"] != 'true' @deliverycharge = @product.deliverycharges.create!(districtrate_id: district.id) delivery_custom_price(district) end ...

How to use Rails #update_attribute with array field?

ruby-on-rails,ruby,postgresql,ruby-on-rails-4,activerecord

I don't think update_attribute is going to be useful as it will replace the array with the new value rather than append to it (but see better explanation below in --Update-- section). I'm not sure what best practices are here, but this should work to just add something if it...