RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

Thank you Andris, been searching online for nearly 3 hours to figure this out for rails 4 using has_many_through!!

This change int the strong params function works for me, but still requires me to use params[:product][:category_ids] ||= [] in my update controller. Otherwise, submitting the form with all checkboxes unchecked does not work. Are you sure that it works for you without params[:product][:category_ids] ||= [] ?

Avatar

jQuery version:

Javascript
function confirm_destroy(event, element, options) {
    if (confirm("Are you sure?")) {
        var f = $("<form>", {
            display: 'none',
            method: 'POST',
            action: options.action
        });
        $(element).parent().append(f);

        var s = $("<input>", {
            type: 'hidden',
            name: '_method',
            value: 'delete'
        }).appendTo(f);

        if (options.token_name && options.token_value) {
            var t = $("<input>", {
                type: 'hidden',
                name: options.token_name,
                value: options.token_value
            }).appendTo(f);
        }

        f.submit();
    }
    event.preventDefault();
    return false;
}
Avatar

Did you ever figure this out? I'm looking to do the same thing.

Avatar

Thanks for reporting that error, I have corrected it.

Avatar

I tried to implement application with ActionController::Live again, and had some troubles with multi-treading. I found it doesn't work. But then discovered, that it actually zsh's repeat command doesn't work appropriately. It sends commands one-by-one. Checked with zsh 5.0.0-2ubuntu1 version.
Also, I tried to check by opening two different Chrome tabs. Same effect, Chrome waits while one request will finish, then sends another.
So multi-treading can be checked either by sending two curl requests from different console tabs, or by using two different browsers.

Avatar

I'm getting this one as well. Does anyone know how to address this?

I'm trying to run:

task :set_file_permissions do
run "chmod -R 777 #{release_path}/public/uploads"
run "chmod -R 0666 #{release_path}/log/production.log"
end

Getting the same errors as above.

Avatar

Thanks for your code, it works great! Except one place need to change, the last 3rd line should be " event.preventDefault(); ", otherwise it causes an "no method stop()" error in the console.

Avatar

I'm on rails4 ruby2.1 and I can't seem to get the tagging table to record the association. Any help will be much appreciated. (doing this from scratch)

ruby
# records.rb

has_many :taggings
has_many :tags, through: :taggings


def tag_list
  tags.map(&:name).join(", ")
end
  
def tag_list=(names)
  self.tags = names.split(",").map do |n|
    Tag.where(name: n.strip).first_or_create!
  end
end
ruby
# tagging.rb

belongs_to :record
belongs_to :tag
ruby
# tag.rb

has_many :taggings
has_many :records, through: :taggings
ruby
# views/records/_form.html.erb

<div class="field">
  <%= f.label :tag_list %><br />
  <%= f.text_field :tag_list %>
</div>
ruby
# records_controller.rb

def record_params
  params.require(:record).permit(:name, :tag_list)
end

The tags do get created in the tag table; but no association defined in the tagging table between the record and the tag.

Avatar

Same. This might be a stupid question but do we need to activate a worker process in order for RedisToGo to work with Sidekiq on Heroku?

Avatar

haha, didn't restart the server

happy! but feeling slightly stupid

Avatar

Oh man, I got so pumped watching his but can't get it to work. Install the gemfile under development

group :development do
gem 'better_errors'
gem 'binding_of_caller'
end

bundle install
bundle update

fire up my app, get to an error, and just the same usual error screen as always.

Running Rails 4 on Ubuntu with Sublime Text 3. Any ideas?

I saw that this is mainly a Mac gemfile but thought that was just for the linking between the error screen and the text editor...

sad.

Avatar

Has anyone every tried implementing an endless scroll up? Trying to do this for an e-commerce site, it mostly works but there are a few bugs that need to worked out. If anyone has done anything like this, I would love to know how you went about it. Thanks

-John

Avatar

How would you create the graph grouped by 2 variables month and employee (for instance)?

ruby
Vote belongs_to :employee
Employee has_many :votes

Vote.chart_data

def self.chart_data(1.year.ago)
 total_count = 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.count_by_month(start)
 enquiries = unscoped.where(created_at: start.beginning_of_day..Time.zone.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

The morris graph expects this type of data for multiple lines

Morris.Line({
element: 'line-example',
data: [
{ y: '2006', a: 100, b: 90 },
{ y: '2007', a: 75, b: 65 },
{ y: '2008', a: 50, b: 40 },
{ y: '2009', a: 75, b: 65 },
{ y: '2010', a: 50, b: 40 },
{ y: '2011', a: 75, b: 65 },
{ y: '2012', a: 100, b: 90 }
],
xkey: 'y',
ykeys: ['a', 'b'],
labels: ['Series A', 'Series B']
});

Avatar

Also, you can use search_field_tag instead of text_field_tag. That will create a text field of type "search".

Avatar

Also, that last part about adding more fields to the search came in very handy, thanks! I was able to add a dropdown list to filter results in addition to the search.

Avatar

there is some issue here when us attr_accessible. i included a gem breaks my shopping cart in my rails app. It works fine when i exclude this gem. Any help is appreciated.

Avatar

As of right now I'm having trouble running this in production with Heroku. Locally I can upload a full-size/thumb-size version of the image to s3, however in production only a full-size image will be uploaded s3. To my understanding it's due to Heroku's support of background jobs, anyone have experience solving this?

Avatar

I think so, in fact this blog outlines ways of joining a Sinatra app with a Rails app basically using warden.

http://labnote.beedesk.com/sinatra-warden-rails-devise

Avatar

I'm still just a little confused about the #container div. There is no #container div in the template, so why and how does that work? Just looking for clarification.

Avatar

Is this prone to SQL injection? It looks like you're directly embedding strings into your SQL queries.

Avatar

For me the whole presenter thing ended up in NameError, so I ended up using this.

+1

Avatar

For anyone who's using Rails 4 and is wondering about projects_path, don't worry. I'm a Rails newbie, but in my experience, Rails adds what you need to your routes file (app/models/modelname.rb) automatically when you create the controller.

If it doesn't, I believe adding the following line does it:

ruby
resources :projects   # Replace "projects" with your controller name

Also, if you're wondering why we use def self.search instead of def search, it's because we want a class method instead of an instance method. In other words, it allows us to do Project.search, we're calling the method from the class, not from an instance of the class.

Avatar

That probably means you're missing the search method in your model.

Avatar

Thanks for this, man! Really helped.

I should mention it's now preferred to add via: :all if using match to address what Keil mentions below.

Avatar

Hi,
if i have

ruby
attr_accessor :date, :count 

where :date is a datetime and :count is a integer, i have this error "NoMethodError (undefined method `data(1i)=' for".

Can i declare :date as a datetime?

Avatar

it worked for me...thanks @wendy hung

Avatar

I'm getting a "The parameter app_id is required" when navigating to http://localhost:3000/auth/facebook. I scanned the comments didn't see anyone with the same issue. It's been two years since the tutorial. I followed it to a T. The only thing different is in routes.rb when I change match to get

Avatar

It works for me. thanks.
Do you know how to write where clause that search in User model for full user name from firstname and lastname attributes. Also you can type only firstname and get result.

Avatar

I new to rails. I don't know if it was possible to use form_tag in view without loud erb tags in earlier or not. But in rails 4 it is not working so code we need to write for this is :-

<%= form_tag('/products', method: :get) do %>

<%= text_field_tag :search %>
<%= submit_tag "search" %>

<% end %>

Happy learning :)

Avatar

Thanks for that nice episode. Again, really helpful!

Avatar

If anyone is interested in a WYSIWYG editor compatible with activeadmin, check out https://github.com/stefanoverna/activeadmin-wysihtml5, is extremely good!

Avatar

At first I had the same thought, but it's not going to work. The css classes are cached too, for all the users, so if the first user happens to be admin, the next users will see the cached admin version of the page. Vice versa, admins might be seeing just the user version of the page.

Avatar

can someone please explain how can i load other apis(e.g. google map api) along with turbolink

Avatar

typo in asciicast:

#{e.mesage} -> #{e.message}

Avatar

I have recently run into this issue and managed to solve it:

It turned out to be turbolinks issue preventing from loading any js on the first page load:
http://stackoverflow.com/questions/17881384/jquery-gets-loaded-only-on-page-refresh-in-rails-4-application

Simple commenting out

application.js
//= require turbolinks

helped me but you can try replacing it with 'jquery-turbolinks' gem as an answer on stackoverflow link suggests.

Avatar

Hi, when I create a new rails app and follow the tutorial, it is impossible to have actioncontroller live working properly. When I check what is going on in the browser, the "events" action is marked as pending.

When I use the app built by Ryan it is working properly. However, if I do "bundle update" the "events" action is not working.

Does someone have an idea what settings I have to change on a new rails app ?

Avatar

I just got this working. I had to adjust the variable localhost to my server's ip address in both the application.html.erb (layout) file and the application.js file.

Avatar

Not sure if you are still having an issue, but jerclark solved this (search this page for "mobile" instead of "iPhone". I missed it for a month):

I resolved it by changing the server property in config/private_pub.yml from "localhost" to my dev server IP address.

You'll need to change it to something that your mobile device can access. Also, if you manually included the private_pub javascript using a javascript_include_tag with an absolute URL to localhost, you'll probably want to change it there as well.

I had to restart the app to make this work.

Avatar

omg thanks allot this saved me so much time.

Avatar

I hate to say it but all the other solutions limit your functionality with using prefixes. The proper way is to follow the documentation here: http://www.postgresql.org/docs/9.1/static/textsearch-controls.html

Replace all spaces with "&"

You can do this in your search method:
query = query.split(" ").join(" & ")

Avatar

This worked with sublime text 2 as well without any modification on Maverick and is the only one only one that actually worked, great application!