RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

Exactly what I was looking for. Sure hope you come back to do more RailsCasts soon Ryan!

Avatar

wow thanks... crazy how things change. Just getting into this now and there's NOO way I would have figured that out

Avatar

I have this issue as well and it's the only thing keeping me from deploying my app right now. I can do a skip_around_filter and the homepage (static pages) will work and so will the subdomain but this is not a good solution on controllers that have actions that either need to be scoped or unscoped. For example, the registrations controller needs to have the new/create actions unscoped so people can register for a new account and then have the edit/update action scoped so only the right user can update their account.

It seems like this railscast should have covered routing. I followed his railscast for subdomains but for some reason, doing a match doesn't do anything in rails 4.2. I think it's still supposed to be working but it has no affect on anything if I use constraints as I've found in the rails casts and on stackoverflow.

I guess I can do the skip filter now and try to be more specific in the registration controller.

Avatar

This was yet another awesome tutorial. I have chosen to go with your custom locking mechanism in my current project. Although I had to figure out my way through using an added time based field in the database as you mentioned at the end of the video, I did make one change to your handle_conflict method, changing the line that reads:

ruby
errors.add name, "was #{values.first}"

to:

ruby
errors.add attribute, "was " + (values.first.blank? ? "blank" : values.first.to_s)

To handle cases where something was added to a blank field during edit.

Avatar

I can't quite wrap my head around this, but while following this tutorial line-by-line, my Backbone app refuses to render the view template. Please point me in the right direction, as this is my first experience with Backbone, and I've been circling around this problem for the past two days.

This is my /entries.js file:

```javascript
class Raffler.Routers.Entries extends Backbone.Router
routes:
'': 'index'
'entries/:id': 'show'

    index: ->
            view = new Raffler.Views.EntriesIndex()
            $('#container').html(view.render().el)


    show: (id) ->
            alert "entry #{id}"```

If I were to replace $('#container').html(view.render().el) with $('#container').html('Raffler') , it would produce the desired outcome. I don't think the el attribute has a value.

My /index.jst.coffee file:

```javascript
class Raffler.Views.EntriesIndex extends Backbone.View

template: JST['entries/index']

render: ->
$(@el).html(@template())
this```

I got error saying that Uncaught TypeError: this.template is not a function

Any help is appreciated!!

Avatar

Excellent screencast, Ryan Bates! I built it in Rails 4 and updated two lines to work with Savon 2. Thanks!

Avatar

Came here with a similar intent to Kraig.

The below gist tracks my changes to Ryan's code that make this project Rails 4.2 + RSpec 3.2 friendly.

https://gist.github.com/tennantje/1ce46a6eb3c66a949efd

Avatar

You can use puts "code" to print a log in your terminal

Avatar

How to use multiple resque with single application.

My aim is:
I am using multiple database postgres in single application.
Is that possible to have multiple resque (each redis for each postgres database)

Avatar

hi i am using scope
i have two collection contact and company

company has_many contact
contact belong to company

condition

scopedData = Contact.scoped
scopedData = scopedData.where(:email => "vinay@gmail.com")
then from this scoped data
want to find where company name is "test"

how to use scoped on this

please help me friends

Avatar

Does anyone know of any updated places to learn about Feedjira? I am running into errors, but can't find a resource to learn about how to set it up correctly in 2015.

Avatar

This doesn't work anymore in Rails 4.2. Instead, use rescue_from.

Example:

ruby
class ApplicationController < ActionController::Base
  rescue_from User::NotAuthorized, with: :deny_access # self defined exception
  rescue_from ActiveRecord::RecordInvalid, with: :show_errors

  rescue_from 'MyAppError::Base' do |exception|
    render xml: exception, status: 500
  end

  protected
    def deny_access
      ...
    end

    def show_errors(exception)
      exception.record.new_record? ? ...
    end
end
Avatar

Hey guys.

DEPRECATION WARNING: link_to_function is deprecated and will be removed from Rails 4.1.

Hope the following codes could help anyone. ;)

First. Pass args by data-["someAttributes] in a link

ruby
- link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
+ link_to(name, "#", "data-association" => "#{association}" , "data-content" => "#{fields}", :class => "link_to_add_fields" )

Then. Add an eventListener to the above link rather than to use link_to_function

ruby
+$(document).on("click", "a.link_to_add_fields", function(e){
+        e.preventDefault();
+        var link = $(this);
+        var association = $(this).data("association");
+        var content = $(this).data("content");
+        add_fields(link, association, content);
+});
Avatar

Hi ,

i need to know that can we implement below payment process using strip payment gateway

User1's Credit card--->fund transfer--to admin strip account-->20% commission deducted for admin--->80% of fund transfer to user2's paypal or bank account.

We are trying to implement this in out site what having the issues in implementation.

Can anybody help in this..

Thanks

Avatar

Hello. Ho could we set nested params inside controller method, if we have many nested params, so that we should iterate over them an set their values to something. I have asked about that here:
http://stackoverflow.com/questions/29901150/how-to-set-values-of-nested-parameters-in-rails-4-from-controller-method

Avatar

when I go to http://production.foo.com/ I get "Apache2 Ubuntu Default Page" does anyone know what happened?

Avatar

If anyone runs into a runtime error when trying to display the omniauth in yaml using this code RuntimeError raise request.env["omniauth.auth"].to_yaml

Try this instead render :text => "<pre>" + env["omniauth.auth"].to_yaml

Avatar

Rails 4

ruby
def category_name=(name)
          self.category = Category.where(name: name).first_or_create if name.present?
  end
Avatar

Hi, how to hide terms that are not present currently in index(deleted from models)?

Avatar

So, this may not be the issue, and I'm too late to help either of you, but in case someone else is looking for this: In Rails 4, you need to use <%= f.fields_for..., not
<% f.fields_for... Note the = after <%.

Avatar

Generally, your Rails application is probably not the best place to consume RSS feeds. Most of it needs to happen asynchronously to prevent your app from becoming slow. It's also a mess to deal with multiple formats and breaking feeds.

For this reason, APIs like Superfeedr exist and we recently introduced a Rails Engine which makes all this very simple and elegant.

Avatar

Ajax search is not working though simple search works fine. I am not getting any error as well in my log file. Following is my code:

show_workers.haml
= form_tag show_workers_agencies_path, :method => 'get' do
= hidden_field_tag :direction, params[:direction]
= hidden_field_tag :sort, params[:sort]
%p
= text_field_tag :search , params[:search]
= submit_tag "Search", :name => nil

workers= render 'workers'

_workers.haml
%table.pretty
%thead
%tr
%th= sortable "name"
%th Phone number
%th City
%th{:colspan => "3"}
%tbody
- @workers_list.each do |worker|
%tr
%td= worker.name
%td= worker.phone_number
%td= worker.city
%br
= paginate @workers_list

show_workers.js.haml
$("#workers").html("#{escape_javascript(render("workers"))}");

agencies_controller.rb
def show_workers
@workers_list = Worker.where(agency_id: current_user.agency.id).order(sort_column + " " + sort_direction).search(params[:search]).page(params[:page]).per(5)
respond_to do |format|
format.html
format.js
end
end

application.js
$(function() {
$("#workers th a").on("click", function() {
$.getScript(this.href);
return false;
});
});

Please tell if I am missing anything.

Avatar

Hi all,

can you help me config action view from 1 2 3 4 5 to default 10 number (1 2 3 4 5 6 7 8 9 10)?
- when I click 1, 2, 3, 4, 5 still (1 2 3 4 5 6 7 8 9 10)
- when I click more than 5 ( display left 4 + current + 5 right)

Thanks all!!!

Avatar

The XML Spreadsheet does not work. :(
My OS X 10.02 and Numbers version: 3.5
what i can see in Numbers are the following
<?xml version="1.0"?>

Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"

xmlns:o="urn:schemas-microsoft-com:office:office"

xmlns:x="urn:schemas-microsoft-com:office:excel"

xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"

xmlns:html="">http://www.w3.org/TR/REC-html40">

Worksheet ss:Name="Sheet1">

Table>

Row>

ID

Name

Release Date

Price

/Row>
........

Avatar

I'm trying to resolve this issue now, are you saying not to remove .pem like Ryan does?

Avatar

Just found a solution.

I need to do this

ruby
def authorize
    if current_permission.allow?(params[:controller], params[:action], current_resource)
      current_permission.permit_params! params
    else
            if current_user.nil?
                    redirect_to new_user_session_path
            else
                        redirect_to root_url, alert: "Not authorized."
            end
    end
  end
Avatar

Hi,

Not work for me with rails 4 got a redirect loop :(

Any idea ?

Avatar

If you're looking for a non-blocking, real time Rails solution, check out Entangled: https://github.com/dchacke/entangled

Avatar

check out here, the geocode actually suggests a way to test it. it's probably something new in their documentation

https://github.com/alexreisner/geocoder#user-content-testing-apps-that-use-geocoder

Avatar

Any best practices about how to test Fragment Caching?

Avatar

What happens if I use method: :get in link_to? Does that make any effect on loading of the page?

Avatar

Do mercury.js have to be in assets/javascripts?
remove //= require_tree . in application.js is the only way to prevent load it on all pages?

Avatar

I know that this is a old post and no one has posted here in 9 month but I having problem with searching numbers any one has a example. thanks

Avatar

If you are still interested, you can checkout my forked repo on github - https://github.com/asang/403-dynamic-forms

Avatar

In order for this to work with Rails 4.0 or later, you have to use http://blog.trackets.com/2013/08/17/strong-parameters-by-example.html and make following changes to app/controllers/survey_controller.rb

--- questionnaire-after/app/controllers/surveys_controller.rb   2012-04-19 10:45:53.000000000 +0530
+++ /home/asang/questionnaire-after/app/controllers/surveys_controller.rb       2015-04-05 19:13:56.746426275 +0530
@@ -12,7 +12,7 @@
   end
 
   def create
-    @survey = Survey.new(params[:survey])
+    @survey = Survey.new(survey_params)
     if @survey.save
       redirect_to @survey, notice: "Successfully created survey."
     else
@@ -26,7 +26,7 @@
 
   def update
     @survey = Survey.find(params[:id])
-    if @survey.update_attributes(params[:survey])
+    if @survey.update_attributes(survey_params)
       redirect_to @survey, notice: "Successfully updated survey."
     else
       render :edit
@@ -38,4 +38,12 @@
     @survey.destroy
     redirect_to surveys_url, notice: "Successfully destroyed survey."
   end
+
+  private
+
+  def survey_params
+       params.require(:survey).permit(:name).tap do |w|
+               w[:questions_attributes] = params[:survey][:questions_attributes]
+       end
+  end
 end
+++ /home/asang/questionnaire-after/app/models/answer.rb        2015-04-05 19:13:56.746426275 +0530
@@ -1,4 +1,3 @@
 class Answer < ActiveRecord::Base
-  attr_accessible :content, :question_id
   belongs_to :question
 end
diff -uwrN questionnaire-after/app/models/question.rb /home/asang/questionnaire-after/app/models/question.rb
--- questionnaire-after/app/models/question.rb  2012-04-19 10:45:53.000000000 +0530
+++ /home/asang/questionnaire-after/app/models/question.rb      2015-04-05 19:13:56.746426275 +0530
@@ -1,5 +1,4 @@
 class Question < ActiveRecord::Base
-  attr_accessible :content, :survey_id, :answers_attributes
   belongs_to :survey
   has_many :answers
   accepts_nested_attributes_for :answers, allow_destroy: true
diff -uwrN questionnaire-after/app/models/survey.rb /home/asang/questionnaire-after/app/models/survey.rb
--- questionnaire-after/app/models/survey.rb    2012-04-19 10:45:53.000000000 +0530
+++ /home/asang/questionnaire-after/app/models/survey.rb        2015-04-05 19:13:56.746426275 +0530
@@ -1,5 +1,4 @@
 class Survey < ActiveRecord::Base
-  attr_accessible :name, :questions_attributes
   has_many :questions
   accepts_nested_attributes_for :questions, allow_destroy: true
 end

Few other changes are required in GemFile

diff -uwrN questionnaire-after/Gemfile /home/asang/questionnaire-after/Gemfile
--- questionnaire-after/Gemfile 2012-04-19 10:45:53.000000000 +0530
+++ /home/asang/questionnaire-after/Gemfile     2015-04-05 19:13:56.751426282 +0530
@@ -1,6 +1,6 @@
 source 'https://rubygems.org'
 
-gem 'rails', '3.2.3'
+gem 'rails', '~> 4.2.1'
 
 # Bundle edge Rails instead:
 # gem 'rails', :git => 'git://github.com/rails/rails.git'
@@ -11,8 +11,8 @@
 # Gems used only for assets and not required
 # in production environments by default.
 group :assets do
-  gem 'sass-rails',   '~> 3.2.3'
-  gem 'coffee-rails', '~> 3.2.1'
+  gem 'sass-rails'
+  gem 'coffee-rails'

and some other files:

diff -uwrN questionnaire-after/config/application.rb /home/asang/questionnaire-after/config/application.rb
--- questionnaire-after/config/application.rb   2012-04-19 10:45:53.000000000 +0530
+++ /home/asang/questionnaire-after/config/application.rb       2015-04-05 19:13:56.739426266 +0530
@@ -48,7 +48,7 @@
     # This will create an empty whitelist of attributes available for mass-assignment for all models
     # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
     # parameters by using an attr_accessible or attr_protected declaration.
-    config.active_record.whitelist_attributes = true
+    #config.active_record.whitelist_attributes = true
 
     # Enable the asset pipeline
     config.assets.enabled = true
diff -uwrN questionnaire-after/config/environments/development.rb /home/asang/questionnaire-after/config/environments/development.rb
--- questionnaire-after/config/environments/development.rb      2012-04-19 10:45:53.000000000 +0530
+++ /home/asang/questionnaire-after/config/environments/development.rb  2015-04-05 19:13:56.739426266 +0530
@@ -23,11 +23,11 @@
   config.action_dispatch.best_standards_support = :builtin
 
   # Raise exception on mass assignment protection for Active Record models
-  config.active_record.mass_assignment_sanitizer = :strict
+  #config.active_record.mass_assignment_sanitizer = :strict
 
   # Log the query plan for queries taking more than this (works
   # with SQLite, MySQL, and PostgreSQL)
-  config.active_record.auto_explain_threshold_in_seconds = 0.5
+  #config.active_record.auto_explain_threshold_in_seconds = 0.5
 
   # Do not compress assets
   config.assets.compress = false
Avatar

My ruby version is 2.0.0p598
rails version is 4.2.1
when i run the server and go to my home page where i put the line <%= subscribe_to "/send_message" %>, the chrome console output "Failed to load resource: net::ERR_CONNECTION_REFUSED",
I don't know how to fix this one

I know there is an alternative way like private pub, which is d'Anthes, and it don't have those errors, but it still won't work

So, anyone help me to make one?

Avatar

Can some one help me use private pub to make messaging project?
I follow the tutorial here, but I don't know why it won't work,
is private pub outdated already?

Avatar

The Tire gem has been retired in favor of the official elasticsearch-rails gem. Is there any chance we can get an updated cast with that? The new gem has decent documentation, but very few examples of real-world usage.

Avatar

so why on earth Ryan did all that work? seriously...

Avatar

Thanks for pointing this out! It saved me a bunch of time!

Avatar

I don't know if someone have encountered this problem so I'm going to ask here. I have implemented this already and it's working but their is a little problem. On the first page all of the javascript are working for example lightbox(html5lightbox), but for the remaining pages that is generated the javascript isn't working.

Avatar

I'm using it in rails 4 ruby 2.2 and isn't working anything I should know?, thks