RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

I don't know much about android, but I would assume you can get the device Id somehow. couldn't you use that as your token and then have your client just send the device id along with the request?

Avatar

I use the less hacky approach to use production dump in performance tests. I simply introduce benchmark environment. I just:

  1. put require_relative 'test' into /config/environments/benchmark.rb so that benchmark environment mimics test
  2. add proper entry to /config/database.yml
  3. possibly add Bundler.require(*Rails.groups(:test => %w[test benchmark])) to /config/application.rb to get gems loaded
  4. begin my performance_test_helper.rb with ENV["RAILS_ENV"] = "benchmark" ; require_relative '../../config/environment'.

I use RSpec for general testing, so this perfectly works for me. You may need further tweaks (esp. in point 4) if you want to use Test::Unit for other tests too.

Avatar

I'm curious if this is the "right" approach for me to use for a particular portion of my application.

I have many tasks and many users. Tasks belong to a particular user, but can be completed by multiple users (defined by a manager role over another model).

Anyway, I want users to be able to opt-in/out of being reminded about certain tasks that they either own or manage.

My thought is to do a has_many :through relationship with a reminder join table.

My interface differs from the one in this railscast in that in the presentation of a task list, there would be just a single check box for each task that determines whether the current logged in user will get reminders for the task.

So I see lots of parallels to this railscast, but I can't seem to get to solution that doesn't feel cludgy. Am I on the right path?

Thanks!

Avatar

@rvsingh, thanks appreciate this, i owe u a beer

Avatar

The following code works for grouping counts by month:

ruby
  def self.chart_data(start = 1.year.ago)
    total_count = total_count_by_month(start)
    start = start.to_date.beginning_of_month
    today = Date.today.beginning_of_month
    range = (start..today).select {|d| d.day == 1}
      range.map do |month|
        {
          created_at: month,
          total_enquiries: total_count[month] || 0
      }
    end
  end

  def self.total_count_by_month(start)
    enquiries = unscoped.where(created_at: start.beginning_of_month..Time.now)
    enquiries = enquiries.group("date_trunc('month', created_at)")
    enquiries = enquiries.select("date_trunc('month', created_at) as created_at, count(*) as count")
    enquiries.each_with_object({}) do |enquiry, counts|
      counts[enquiry.created_at.to_date] = enquiry.count
    end
  end
end

date_trunc is a postgresql function.

I've yet to find a way to format the date output to "%b %Y" instead of the default format.

If anyone has a better solution please share!

Avatar

Ive been getting the following error "You must supply a valid card" i cant seem to find any info on the stripe docs, have any of you been getting this lately?

Avatar

I've found the after_touch method a good place to clear the cache too

ruby
after_commit :flush_cache
after_touch :flush_cache
Avatar

I have successfully implemented the calendar with a grouping by start date. However, my events span over weeks. How can I convert my events to span from start date to end date?

Thanks!

Avatar

When I call recreate_versions! method a new file is generated and older files are kept on uploads directory. What's the best way to remove older files after recreating versions?

Avatar

I have issue integrating tokeninput facebook them with bootstrap modal. I googled the issue and it looks like a z-index problem. But I cannot get it working after trying every solutions. I would really appreciate if there could be a tutorial on tokeninput with bootstrap (maybe with modal)

Avatar

I was wondering if any one knows of good solutions for polymorphic HABTM relations. Like the relationship between tags products and articles. I've seen some decent hacks involving join tables but they all require hard coding each evolved model in the join table.

Avatar

If you don't want to dig through all the modules, use the default:

class Message
  include ActiveModel::Model
end

This is pretty handy, because it already extends Naming and Translation, and includes Validations and Conversion. And it comes with a nifty initializer that allows to pass attributes in Message.new(title: "...") and offers a persisted? method.

See: https://github.com/rails/rails/blob/master/activemodel/lib/active_model/model.rb

Avatar

If I include all the JS assets in the head everything seems to broke...
Does it work for you? Have you modify anything else?

Avatar

Hi Ryan,
Good screencast and help all newbies to learn rails easily.
I am using rails 4 and encountered one problem.

In password_resets_controller.rb you do:

elsif @user.update_attributes(params[:user])

IN console it showing
ActiveModel::ForbiddenAttributesError in PasswordResetsController#update

I don't know how to solve this issue.Please help me to solve this issue.

Avatar

I have a problem in using the dynamic select menu along with nested attributes. please help me . I have posted my question in http://stackoverflow.com/questions/17546917/how-to-include-both-dynamic-select-menu-and-nested-attributes-together-in-rails

Avatar

This is the default behavior when clicking on a link with an href="#". Make sure that whatever javascript your using to add or remove fields includes an event.preventDefault() call. In coffeescript, this should look something like the following for nested fields but can easily be applied to any click event where you need to suppress the default behavior for a given event:

app/assets/javascripts/nested_forms.js.coffee
jQuery ->
  $('form').on 'click', '.remove_fields', (event) ->
    $(this).prev('input[type=hidden]').val('1')
    $(this).closest('fieldset').hide()
    event.preventDefault()

  $('form').on 'click', '.add_fields', (event) ->
    time = new Date().getTime()
    regexp = new RegExp($(this).data('id'), 'g')
    $(this).before($(this).data('fields').replace(regexp, time))
    event.preventDefault()
Avatar

Wonderful screen cast. The instructions on the github page are sort of daunting but you make things crystal clear!

Avatar

Has anyone know how to move create method into worker?

photos_controller.rb
def create
    @project = Project.find(params[:project_id])
    @photo = @project.photos.build(params[:photo])
    @photo.user = current_user
    if @photo.save
      redirect_to image_upload_project_path(@project)
    end
end
Avatar

In the code !params[:redo] is going to evaluate the truthyness of an instance of String. Even though the contents of that string is 'true' or 'false' !params[:redo] will evaluate to false every time. This will cause your users to get stuck in a loop where 'redo' link is always displayed.

I would make the following changes to the rever action.

link_name = (params[:redo] == "true")? "undo" : "redo"
is_redo = false
is_redo = (params[:redo] == 'true')? true : false if params[:redo]
link = view_context.link_to(link_name, revert_version_path(@version.next, redo: !is_redo), :method => :post)
flash[:success] = "Undid #{@version.event}. #{link}".html_safe
redirect_to :back
Avatar

Can anyone provide anything on this subject? I'm really looking myself.

Avatar

If you would rather not use rvm or rbenv here's a link on how to build ruby from source:

https://github.com/yerv000/how_to-ruby_from_source

Avatar

Hello, this is a great course and is working perfectly but I am having trouble with Client-side Image Resizing. I followed:
https://github.com/blueimp/jQuery-File-Upload/wiki/Client-side-Image-Resizing

I added 3 lines but it doesn't work
$("#fileupload").fileupload
disableImageResize: false
imageMaxWidth: 800
imageMaxHeight: 800
...

Does anyone have a working example?

Thank you for any help

Avatar

Do you know what the tax on SQL would be for this? I just used one reputation to count positive (votes up) and another to count negative (votes down).

Avatar

For what it's worth, bootstrap has a SASS version. Take a look at the bootstrap-sass gem.

Avatar

Try uncommenting and putting in values for :web_tools_user and :web_tools_password in rubber.yml. It solved the problem for me.

Avatar

I use request.subdomains.first rather than request.subdomain as recommended by DHH: http://37signals.com/svn/posts/1512-how-to-do-basecamp-style-subdomains-in-rails

If you use request.subdomain and use an IP address as the URL, request.subdomain will include the IP address.

Avatar

Does anyone know why I get the error:

undefined local variable or method `new_user_session_url' for #Doorkeeper::AuthorizationsController:0x007fef99668bc8

resource_owner_authenticator do
# Put your resource owner authentication logic here.
# Example implementation:
current_user || redirect_to(login_url)
end

I am using Sorcery with Doorkeeper

Avatar

In the latest version of rspec, I'm getting errors like:

ruby
  1) Permission as guest allows sessions
     Failure/Error: should allow(:sessions, :new)
     ArgumentError:
       wrong number of arguments (2 for 1)
     # ./spec/models/permission_spec.rb:20:in `block (3 levels) in <top (required)>'
     # -e:1:in `<main>'

It seems the matcher is not valid anymore?

ruby
RSpec::Matchers.define :allow do |*args|
  match do |permission|
    permission.allow?(*args).should be_true
  end
end

How would you rewrite it so that it works with the latest rspec?

Avatar

New subscriber here - Thanks for all your work Ryan

Avatar

I ran into the exact same issue. Thanks for sharing, really helped me out.

Avatar

Hi Ryan, Thanks for this great episode. In your submit code:

ruby
def submit(params)
    ....
    if valid?
      @user.password = new_password
      @user.save!
      true
    else
      false
    end
 end

I think you better use @user.save instead of save!. The reason is that your submit method can then only return true or false:

ruby
if valid?
  @user.password = new_password
  @user.save
else
  false
end

As someone who reads your code, i dont expect to see user validation errors on password submit method.

Avatar

I totally agree, Igor.
I would have a ProductCollection model (not an AR model, but more of a form object wrapping the collection of Product objects) and a ProductCollectionController. It's much cleaner than forcing collection behaviour into the Product and ProductsController classes.

Avatar

One thing to mention is that in the routes file, the default version has to be the last one to be defined.
I had a problem where I added a v2 on top of v1 and made it the default like this:

routes.rb
...
namespace :api, defaults: { format: 'json' } do
  scope module: :v2, constraints: ApiConstraints.new(version: 2, default: true) do
  ...
  end
  scope module: :v1, constraints: ApiConstraints.new(version: 1) do
  ...
  end
end
...

All V1 requests would be redirected to the V2 Controllers

Avatar

I'm trying to make the nav-bar collapsible but I'm not sure how to do it. Using the code above did not work. From inspection I see I need to have the toggle element but I'm unsure how to use it.

Avatar

You can very much do this. We have a symbol syntax for this:

tracked owner: :user

this will execute the user association on the tracked object.

Avatar

Not sure what you mean. Do you want to find activities with a specific owner?

Avatar

Just to reply, it works for a couple of months now on stable :)

Avatar

Yes, you can. You can freely extend the Activity model with additional columns and methods from other gems. See the Common examples section in README.