Menu
  • HOME
  • TAGS

Strange has_many Association Behavior in Rails 4

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

So, I went and looked at code of mine that does a similar function. Here's what my create method looks like. This is creating a Student with assignment to Student Groups in a school setting (I didn't use "class" since Ruby wouldn't like that). def create @student = Student.new(student_params) if...

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

ApplicationController helper method undefined in Rails

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

It seems that the problem is that skip_after_action does not accept a conditional argument such as if: or unless:. Even if you pass a conditional, the skip_after_action callback always executes. Unfortunately for me, this means that it is not possible to do what I wanted to do with the code....

rails has_many at least one children has the value

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

You can use joins method. Group.joins(:users).where("users.mood = ?", User.moods[:good]) You can add this into your migration add_index :users, :group_id ...

Rails 4, ActiveRecord SQL subqueries

sql,ruby-on-rails-4,subquery,select-n-plus-1

Here are two ways of doing it: parent.rb class Parent < ActiveRecord::Base has_many :children # Leaves choice of hitting DB up to Rails def age_of_oldest_child_1 children.max_by(&:age) end # Always hits DB, but avoids instantiating Child objects def age_of_oldest_child_2 Child.where(parent: self).maximum(:age) end end The first method uses the enumerable module's max_by...

.where attribute of nested attribute attribute = string

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

You are probability looking for an association like the below: class Injury < ActiveRecord::Base belongs_to :injury_type end class InjuryType < ActiveRecord::Base belongs_to :body_group has_many :injuries end class BodyGroup < ActiveRecord::Base has_many :injury_types end In this way, you can simplify the query: Injury.joins(:injury_type).where(body_group_id: 1).count ...

Why do I keep getting 'undefined method' when it's worked fine before?

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

Check Fields of the Order Model. Do you have listing_id as a column on the orders table ? Check the migration files to make sure that somewhere along the way you have added a "listing_id" field to the "orders" table.

undefined method `after_create' for Controller:Class

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

after_create is a model callback. Not a controller callback. If you want to add a callback which is run after your create method you would do: after_action :send_email_to_subscribers, only: [:create] But, this still occurs before the response is sent and will slow down your response times! You should consider using...

Rails 4: Submit button not responsive after its been reloaded by Ajax

ajax,ruby-on-rails-4,submit,reload

Perhaps the reason in wrong html. about_me_change partial may look like this: <div id="AboutMeForm"> <div class="UserEditsJS"> <%= simple_form_for(@user, remote: true) do |f| %> <%= f.field :about, as: :text %> <%= f.button :submit %> <% end %> </div> </div> Pay your attention that simple_form_for method receives a block which will be...

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' %>)...

Let flash messages disappear by clicking it, in Rails

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

Try giving it like this <div class="alert alert-info alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <% flash.each do |message_type, message| %> <%= content_tag(:div, message, class: "alert alert-#{message_type}") %> <% end %> </div> Update This should work <% flash.each do |message_type, message| %> <%= content_tag :div, class: "alert...

Creating associations with new() versus create()

ruby-on-rails,ruby-on-rails-4,associations,activemodel

As you will be able to notice, when you are using 'new', the id for the new event is not generated. The id for a record is generated only at the time it is saved to the database and two records are linked through their ids only if you haven't...

Use chop before resize in Imagemagick

ruby-on-rails-4,imagemagick,paperclip

solved it with +repage and not in :all so essentially it looks like all: "-limit memory 64 -limit map 128", mobile_sm: lambda{ |instance| "#{!instance.chop_top.blank? ? '-chop 0x31 +repage' : '' } -resize 640 -quality 90 -strip -interlace Plane"}, mobile_lg: lambda{ |instance| "#{!instance.chop_top.blank? ? '-chop 0x31 +repage' : '' } -resize...

Rails add hash into existing hash

ruby,ruby-on-rails-4

The solution is convert to hash result after select from db using @user.as_json a = Hash.new a[:profile] = @user.as_json a[:profile][:contacts] = @user.contacts.all ...

Twitter Boostrap in Rails

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,twitter-bootstrap-3,rubygems

I was able to work it out by moving my project into another directory, preferably into a different folder.

Rspec, can you stub a method that doesn't exist on an object (or mock an object that can take any method)?

ruby-on-rails,ruby-on-rails-4,rspec,rspec-rails,stub

RSpec provides no special mechanisms to access elements under test, so yes, you would need to somehow stub the id method and have it return whatever you wish (e.g. 1). To do that, you must have a way to access the event object in your test so that you can...

Why are parentheses mandatory when using route helper methods?

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

method_name param, other_method other_param is not possible in Ruby, so it's not possible with route helpers either because it is ambiguous. There's even a section about this in The Ruby Programming Language by Matz. Example: irb(main):001:0> def link_to(a, b) irb(main):002:1> puts a, b irb(main):003:1> end :link_to irb(main):004:0> def foo(a) irb(main):005:1>...

How do I add extra data to model before submit from form in Rails

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

You can use the hash options of the ActiveRecord::Core#new method in your controller: @user = User.new(user_params.merge(referrer_url: create_url)) Or move all that into a separate method for a clearer and more readable code: @user = User.new(user_params_with_additional_data) private def user_params_with_additional_data user_params.merge(referrer_url: create_url) end ...

why when uploading a file using carrierwave in rails 4 i get 'rollback transaction'?

ruby,ruby-on-rails-4

Comment these lines from CvattachmentUploader def extension_white_list %w(jpg jpeg gif png) end Restart server and try again. ...

Creating a object with nested form rails

ruby,ruby-on-rails-3,ruby-on-rails-4,nested-forms

Your meeting_params should be like this def meeting_params params.require(:meeting).permit(:meeting_name, :meeting_description, :meeting_date, :agenda_id, meeting_has_members_attributes: [:id, :member_id]) end Notice that I added :member_id in meeting_has_members_attributes and removed members_attributes as you are not saving them....

in ActiveRecord::Relation, is it preferable to scope by parent in the model or set @parent in the controller

ruby-on-rails-4,activerecord,model-view-controller,scope,parent-child

Not sure whether it's possible, but it will couple most of your app to the default_scope implementation, which IMHO is a very bad idea. You might end up needing to change this implementation down the line, which is going to have pretty high impact. It will also make your unit...

Rail Action View Page: Missing Rails Console

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

I think this is what you after: group :development do gem 'web-console', '~> 2.0' end Then use this in your view: <% console %> Reference: https://github.com/rails/web-console ...

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

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

Where is the defination of rails validators?

oop,ruby-on-rails-4

These are Rails methods: You can find valid? here and its code on Github. Likewise with new_record?, you can find a description and its source code here. Also, here is a link to the Rails repository on Github. These methods are not defined in the project, they are defined in...

Rspec test public controller method passing params to private controller method

ruby-on-rails,ruby-on-rails-4,rspec,controller,rspec-rails

Stubbed methods return nil by default. Use and_return to specify the value returned by the stub:: StripeService.should_receive(:new).and_return(whatever) or using the newer syntax expect(StripeService).to receive(:new).and_return(whatever) EDIT Pardon my hand-waving. Your stub must return an object that will act like an instance of StripeService to the extent required for the purposes of...

Using the Rails console to delete odd-numbered records

ruby-on-rails-4,command-line,console

You can use Hero.where('id MOD(2)!=0').destroy_all ...

How to add angular attribute directive to input in rails slim template?

angularjs,html5,templates,ruby-on-rails-4,slim

Try using parenthesis syntax: input#title.form-control(type='text' ng-model='product.title' server-error) This should also work: input#title.form-control type='text' ng-model='product.title' server-error=''...

AWS Beanstalk - Passenger Standalone not serving web pages after Rails 4.2.1 migration

ruby-on-rails,ruby-on-rails-4,amazon-web-services,passenger,elastic-beanstalk

I finally figured out how to increase the logging level for Passenger Standalone (blogged here). From the log, I could see that the web server was responding to the Beanstalk health check with 301 redirects. That meant that the load balancer thought the app was dead, so it was sending...

Shows image path rather then the image, within one-line if..else statement

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

That's a really weird way to write some erb template code. As @mudasobwa says you have quotes around the image tags which is wrong, and adding lots of strings together in the erb tag is messy, fragile and unreadable. The two image tags are almost identical so could be dried...

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

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

implement has_many through association in rails 4

ruby-on-rails-4,activerecord,has-many-through

Please try this code def inventory_status @employee_inventories = EmployeeInventory.new(employee_inventories_params) if @employee_inventories.save redirect_to inventories_path else render :action => :show end end and in your view <%= link_to 'Request for inventory', inventory_status_inventory_path(@inventory, employee_inventory => {:employee_id => 1, :status => 'test'}), :class => 'btn btn-success' %> hope this will help you....

Invalid form submission clears session in Rails 4

ruby-on-rails-4,session-cookies,form-submit,session-state

Yes it looks like you dropped the '@' in a couple of places in your Create action: if current_customer @order.customer = current_customer end Should be: if @current_customer @order.customer = @current_customer end ...

Change many-to-many association to one-to-many

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

You can change the model's to: class User < ActiveRecord::Base has_many :partners end class Partner < ActiveRecord::Base belongs_to :user end And Partner model should have a user_id column If you don't have a user_id column in Partner model, you can add it by: rails g migration add_user_id_to_partner user_id:integer The intermediate...

How to limit access in Amazon S3 files to specific people?

ruby-on-rails-4,amazon-s3

It is not recommended to use AWS Identity and Access Management (IAM) for storing application users. Application users should be maintained in a separate database (or LDAP, Active directory, etc). Therefore, creating "one bucket per group" is not feasible, since it is not possible to assign your applications users to...

Order of including Helpers in ViewControllers

ruby,ruby-on-rails-4,method-overriding

Any controller can have a corresponding helper. For example if you have a controller named Question (questions_controller.rb), it can have a helper named questions_helper.rb. The question helper is accesible only to the views corresponding to the question controller. Besides you will have an Application helper (application_helper.rb) which is accessible to...

Rails routing link to specific show

ruby-on-rails-4,routing

rails generate migration AddPermalinkToPages permalink:string After you added then you need to create the permalink on the fly when you are saving the page or updating it. I usually do it in the model so I keep the controller clean. You can define it in a PagesHelper if you want...

Rails - Saving Objects with NOT NULL constraint

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

Your result is anomalous. This is what I get: # migration class CreateIssues < ActiveRecord::Migration def change create_table :issues do |t| t.string :path, null: false t.timestamps null: false end end end Then in the console: Issue.create path: "path" # (0.1ms) begin transaction # SQL (0.3ms) INSERT INTO "issues" ("path", "created_at",...

Facing issues with inflections in rails?

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

The problem is : when its trying to render leaves/new its searching for Leaves constant according to your new inflector. Change it to ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.irregular 'leave', 'leaves' end ...

ActiveJob: how to do simple operations without a full blown job class?

ruby-on-rails,ruby,ruby-on-rails-4,delayed-job,rails-activejob

ActiveJob is merely an abstraction on top of various background job processors, so many capabilities depend on which provider you're actually using. But I'll try to not depend on any backend. Typically, a job provider consists of persistence mechanism and runners. When offloading a job, you write it into persistence...

Organize lecture with chapter and lesson models

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

You might want a lambda scope block. Try this: class Lecture < ActiveRecord::Base has_many :chapters, -> { order(number: :asc) } has_many :lessons, through: :chapters end class Chapter < ActiveRecord::Base belongs_to :lecture has_many :lessons end class Lesson < ActiveRecord::Base belongs_to :chapter has_one :lecture, through: :chapter end got it from Deprecated warning...

How to properly define Rails routes so that some actions of a resource go to one controller and some go to another?

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

REST über alles: Much of the the cruft in your routes file could be cleaned up by just sticking the rails REST conventions. This should also improve the consistency of your application. I believe that in many cases your are compromising the design of your application just to get short...

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

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

Seem to be pretty straightforward: https://github.com/ryanto/acts_as_votable#examples-with-scopes @item.vote_by voter: @user1, vote_scope: 'blue' @item.vote_by voter: @user2, vote_scope: 'red' @item.votes_for.size # => 2 @item.find_votes_for(vote_scope: 'blue').size # => 1 @item.find_votes_for(vote_scope: 'red').size # => 1 So you'll need a set of 5 radio buttons (for 5 colors) on your page for the user to select...

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

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

DIsable multiple dates in pickadate.js

jquery,ruby-on-rails,ruby-on-rails-4,pickadate

Hi please try this may be this will help you out var dates = $( '.new_leave_datepicker' ).pickadate(); picker = dates.pickadate('picker'); jQuery.each(gon.holidays, function( val ){ var newDate = new Date(val); disableDate = picker.get("disable", [newDate]); }); ...

Unread messages counter [on hold]

javascript,mysql,ruby-on-rails,ruby-on-rails-4,private-pub

I would argue that your domain modeling is really off. The whole idea of a conversation is that the parties involved take turns being the the sender and recipient. What your have modeled is a monologue. A monologue is a speech delivered by one person, or a long one-sided conversation...

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

Rails 4 wicked_pdf generate blank pdf while generating from model

ruby-on-rails-4,wicked-pdf

A good test is just put a simple line of text in your template and see if you get a PDF with that line. Strip everything back so you just generating a PDF with no coming locals, just that 1 string and let me know. Here is how I set...

RSpec controller test error: controller does not implement method

ruby-on-rails,ruby-on-rails-4,rspec,devise

You're stubbing create_stripe_customer as a class method, but it's actually an instance method.

How to send nested data in response , rails4?

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

This is something that you need to handle in the views with a proper response builder. While acts_as_api suggested by @rob works, Rails starting from v4.0 has built in support for building and sending rich JSON responses using a typical builder style DSL. It is called jbuilder - https://github.com/rails/jbuilder Just...

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

I18n month translation

ruby-on-rails,ruby-on-rails-4,internationalization,rails-i18n

controller: @previous_month = Date.today - (1%12).months view: I18n.l @previous_month, :format => "%B" ...

Ruby on Rails - How to delegate error messages from nested model

ruby-on-rails,ruby,ruby-on-rails-4,mongoid,paperclip

Rails has the validates_associated helper (also available in Mongoid) which will call valid? upon each one of the associated objects. The default error message for validates_associated is "is invalid". Note that each associated object will contain its own errors collection; errors do not bubble up to the calling model. Rails...

Virtual Attribute in Rails 4

ruby-on-rails,ruby,ruby-on-rails-4,virtual-attribute

Instead of using attr_accessor you could create custom getter/setters on your product model. Note that these are not backed by an regular instance attribute. Also you can add a validation on the supply association instead of your virtual attribute. class Product < ActiveRecord::Base belongs_to :supply ,dependent: :destroy validates_associated :supply, presence:true...

create elasticsearch query with optional params

ruby,ruby-on-rails-4,elasticsearch

UPDATE (previous answer removed because it was wrong) After reading a bit about elastic search I think this will work for you def to_es_query { query: { bool: { must: musts } } } end def musts @musts ||= [{ match:{ title_en: @title } }] #possibly { term: {type: @type...

heroku pgbackups:url command is no longer working?

ruby-on-rails,postgresql,ruby-on-rails-4,amazon-web-services,heroku

To download backup b004 use the following syntax: curl -o b004.dump `heroku pg:backups public-url b004` That will download the backup as b004.dump in the current directory....

Can't update existing records in Rails app

ruby,ruby-on-rails-4,simple-form

This is what I ended up doing, based off this (replacing the word user with event): https://www.railstutorial.org/book/updating_and_deleting_users#sec-unsuccessful_edits events_controller.rb: def update @event = Event.find(params[:id]) if @event.update_attributes(event_params) # Handle a successful update. else render 'update' end end Maybe deleting the else render 'update' might avoid the blank "update an event" page that...

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

links from excel to rails server running devise not working properly

excel,ruby-on-rails-4,devise

I found this after I posted, worded differently, but same issue, the first answer was a workaround to my problem. Excel links not loading pages, but when the link is pasted in the browser it works....

Rails - Associate user to review

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

So what you want is to create a new review in two scopes at once: in @venue.reviews and current_user.reviews). Oh hang on, the latter is not even defined? Let's define that on User first: has_many :reviews Then instead of just @venue.reviews use a combination of two scopes: @venue.reviews.merge(current_user.reviews).create(review_params) # ^----------------this...

“Next” button creates a Viewed_Lesson | Ruby on Rails 4 | Learning App

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

It should look like following: class ViewedLessonsController < ApplicationController before_filter :set_user_and_lesson def create @viewed_lesson = ViewLession.new(user_id: @user.id, lession_id: @lesson.id, completed: true) if @viewed_lesson.save # redirect_to appropriate location else # take the appropriate action end end end In your ApplicationController class, you can do: def set_user_and_lesson @user = User.find_by_id(params[:user_id]) @lesson =...

Rails: Override application.css

css,ruby-on-rails,ruby-on-rails-4,haml

The problem you're having is with CSS specificity. You have declared the css files in the right order. However, the rule within tour.css.scss has a lower level of css specificity and therefore cannot override the declaration in application.css.scss. To solve you can do one of three things: Rewrite the rule...

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

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

How to display acts_as_taggable tags on a page with the posts underneath each tag in Rails?

ruby-on-rails,ruby,ruby-on-rails-4,acts-as-taggable-on

You need to iterate each one of the posts per tag on your controller: def index @user = current_user @tags = @user.owned_tags end on your view: <div class="tag-lists"> <% @tags.each do |tag| %> <div><%= tag.name %></div> <% @user.posts.tagged_with(tag.name).each do |post| %> <div><%= post.title %></div> <% end %> <% end %>...

How to make a form_for each object in an instance variable? Rails 4

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

I think that the problem here is the fact that you are accessing the Trackable object directly in the form, but you have no actual path to address the Trackable without accessing the Graph first. Ie. you have a graph_trackables_path() and graph_trackable_points_path() methods, but no trackable_points_path() method. Probably you should...

How to check status of invitation?

ruby-on-rails-4,devise,devise-invitable

Yes you should take a is_registered:boolean column in user table which contains default value "false". Now you just have to do is when user get registered that time you just change value to "true". when ever you want to check is user registered? just do @user.is_registered? or current_user.is_registered? this returns...

Redirect to edit page automatically if record exists

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

A redirect is a fresh request to Rails. You need to set @sale again in the edit action as it is not persisted from update. Alternatively, you can render the edit view directly from update if the update fails. That will preserve the instance variables from update....

Devise emails are not being sent using sendgrid while other emails are being sent well

ruby-on-rails-4,heroku,devise,sendgrid

If you switch config.raise_delivery_errors to true then you'll be able to see if there's a specific problem and work backwards from there.

Multiple many-to-many association between two models

ruby-on-rails-4,activerecord,associations

I guess your association set up should be something like this #user.rb Class User has_many :company_admins has_many :companies, :through => company_admins has_many :followers has_many :followed_companies, :through => followers, :source => :company end #company.rb Class Company has_many :company_admins has_many :users, :through => company_admins has_many :followers has_many :followed_users, :through => followers, :source...

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

Why isn't the format date of the Rails view being properly displayed with the initializer?

ruby-on-rails,ruby,ruby-on-rails-4,erb,view-helpers

You've set the default Date format, but you said that the column is a datetime. If you want the default Date format that you specified, you'll need to convert the value to a date: <%= movie.release_at.to_date.to_s %> ...

Trouble in RSpec test - saving parent record twice

ruby-on-rails,ruby-on-rails-4,activerecord,rspec,nested-attributes

The issue is in sign_up_spec.rb. Your test has a let for user, which means the first time you mention user in your tests it will create a user. However, your application code is supposed to create the user itself. As I said in the comment, this is why in your...

Rails - How to find tilt version?

ruby-on-rails-3,ruby-on-rails-4,sprockets,tilt

Use bundle show to get the versions of your installed gems. For a particular gem, like tilt, you can use bundle show tilt.

How to avoid duplicates from saving in database parsed from external JSON file with sidekiq in Rails

ruby-on-rails,json,ruby-on-rails-4,sidekiq

This is a terrible solution btw, you have a huge race condition in your read/store code, and you're not going to be able to use a large part of what Rails is good at. If you want a simple DB why not just use sqlite? That being said, you need...

Facing issue in edit-update action in nested form in rails4?

ruby-on-rails,ruby-on-rails-4,nested-forms

The problem is in your question_params. You have to add :id for edit/update to work correctly else it will create new records on every successful submit. def question_params params.require(:question).permit(:id, :content, choices_attributes: [:id, :option, :is_correct, :question_id]) end ...

How to validate in database for uniqueness?

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

You need to put this validation into you Api model: validates :name, uniqueness: { scope: :status, message: 'your custom message' } http://guides.rubyonrails.org/active_record_validations.html#uniqueness...

Capybara::ElementNotFound radio by id

ruby-on-rails-4,capybara

You are mapping a label and trying to treat it as a radio? perhaps map the input which has type=radio, most likely then you will be able to use choose method for that element: choose("i-20-1") not sure if you really need the # prior to the id for choose method......

How to iterate data from database to become a radio button in template?

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

You can iterate all the Status records (*). In your controller, you can add: @statuses = Status.all And in your view: <%= form_for @api, :url => commons_path do |f| %> <div class="form-group"> <%= f.label :status, "Status", class: "col-sm-2 control-label" %> <div class="col-sm-8"> <% @statuses.each do |status| %> <%= f.radio_button :status,...

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 how to save date_select field value in date field in db

date,ruby-on-rails-4

Try saving it like this @user.brithdate = Date.new(params[:user]["birthdate(1i)"].to_i,params[:user]["birthdate(2i)"].to_i,params[:user]["birthdate(3i)"].to_i) @user.save ...

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

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

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

Search does not return any value in Rails 4

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

Change your code "%#{:search}%" to "%#{search}%" def self.search(search) if search self.where("area LIKE ?", "%#{search}%") else self.all end end Hope it helps!...

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

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

How do I make a query search in rails case insensitive?

ruby-on-rails,postgresql,ruby-on-rails-4,search

Because you are using postgresql: def self.search(query) where("description ilike ?", "%#{query}%") end Just use ilike instead of like. like/ilike documentation If you want to use =, both sides either UPPER or LOWER...

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

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

Get X days out of an Array

ruby,ruby-on-rails-4

I would do: def get_days(wkn, *desired_days) get_week = Model.week(2) get_days_of_week = get_week.select { |x| desired_days.include? x.strftime("%A") } end ...

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

Rspec can't stub where or find_by_, only find

ruby-on-rails,ruby-on-rails-4,rspec,rspec-rails,stub

Ok I have a temporary solution, which is just to use select. I.e., #run code @current_plan = Plan.select { |p| p.stripe_subscription_id == event.data.object.lines.data.first.id }.first #test code @plan = Plan.new Plan.stub_chain(:select, :first).and_return(@plan) #result of @current_plan (expecting @plan) => @plan Still though... if others have thoughts please chime in... I'm now a...