RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

While it is true that Swing event handling must all be done on that thread, it is not necessary for creation or starting of the initial Swing component needs to happen on that thread. Swing programs routinely have their first setVisible called on the main thread. I don't know if I'll be able to insert a link here, but here is an example on Oracle's site that launches the GUI by calling setVisible on the main thread: http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/BorderDemoProject/src/components/BorderDemo.java

Avatar

Careful on saving DynamicFormEntries field name.
I had to use the field id because of certain field names were rails reserved words which cannot be used.

Avatar

FYI: Ryan is way too busy to maintain this gem so the community has taken it over and is keeping it updated. You can find the latest version here:

https://github.com/cancancommunity/cancancan

Avatar

If you don't want Factory Girl to hit your database, you can try using build_stubbed.

ruby
user = FactoryGirl.build_stubbed(:user)
Avatar

I can very well make a Capistrano task to start private_pub, but how do I make a task to stop it?

Avatar

Exclusively in regard to excel sheets, I understand why it's necessary for csv files.

Avatar

Is .to_hash totally redundant? Isn't row already a hash when product.attributes is assigned it's value?

Avatar

The answer is:

.join("
").html_safe

Avatar

Thanks, after banging my head on the wall for too long this saved me! :)

Avatar

Yes, this railscast is for Celluloid v0.11.1, the latest version is 0.15.2 where they have changed the way dispatching method calls. It either needs an update or a warning stating the version.

Avatar

Hi,

I want to create a dynamic form but there is no model associated with the nested form. I get errors when trying to implement what Ryan has told. Anyone knows how to get around it?

Avatar

Ryan, thanks for this intro. A nicer example would have been in one where you show how angular can help client side validations especially since client side validations is not well maintained.

Avatar

Back to this article... has anyone used this technique with Puma?

Avatar

What is wrong with my coffeescript?

The JSON.parse line is causing the site to fail.
I cannot use var either.

jQuery ->
$percentage_neti = JSON.parse($('#vote-data'))
$('.bar-neti').css("width", $percentage_neti + '%')

(the last two lines are indented)

Avatar

Hi all

I have a products table with server side response.

But I am getting issue with sorting for comments_count. Because comments_count is not a field in products table .

I am getting PGSql error for undefined column comments_count.

But comments_count is the total number of counts for each product record.

def sort_column
columns = %w[name created_at user_id id category_name comments_count]
columns[params[:iSortCol_0].to_i]
end

How can I solve to order by comments_count ?

Avatar

If you don't want to deal with them I wrote a Heroku Add-on that handles them for you: https://addons.heroku.com/expeditedssl

Avatar

Yes, there are some changes with how routes are defined in Rails 4.

Go into config/routes.rb and change your /auth/:provider/callback route to accept :post requests:

ruby
# Rails 4 route syntax
match '/auth/:provider/callback', to: 'sessions#create', via: [:get, :post]
# or, explicitly accept post requests
post '/auth/:provider/callback' => 'sessions#create'
Avatar

Ah came across the cause, needed to add the order rows :id to my permitted parameters. All good now.

http://stackoverflow.com/questions/18946479/ror-nested-attributes-produces-duplicates-when-edit

Avatar

I am using the "link_to_add_fields" helper as used in this screencast in my "Order" model, in the order form you can "add row". It all works ok. But when editing an order, example: /order/1/edit", if the form had 5 rows, when I save the edits it saves the form with 10 rows, if form has 3 rows it saves it with 6 etc. Anybody else run into this issue?

Avatar

Hi i use rails 4.

I have a loop in my url when i put bad locales : example : site.com/zz/

It's look like : site.com/en/en/en/en/en/zz/

In my config/routes.rb i have :

config/routes.rb
match '', to: redirect{|params| "/#{I18n.default_locale}"}, via: :all
match '*path', to: redirect{|params| "/#{I18n.default_locale}/#{params[:path]}"}, via: :all

Does anyone have the same issue ?

Avatar

Thank you so much. Simple, elegant, better.

How could you use the retrieved data as CSS attributes or element names?

1)
Once I have the rails data in js, how would I use that value to set the width of a vote bar div to that calculated percentage value?

Something like

$('.vote-bar').css("width", "#{percentage}%");
But I know the syntax is not right.

2)
How could I also use the rails text data as the name of a class? If my rails data returns 52 via json, I want to select an element named $('#item-52') in js...

Avatar

Has anyone tried to implement an Activity tracker (see ep. 407, et.al) with this?

Avatar

Why is the guard-rspec gem in the test environment group, while on the project's README it says to put it in the development group?

Avatar

In addition to the reasons that gaeldeest mentioned:

  • manual testing is slow if you have to repeat the manual test every time you make a change that could affect it
  • manual testing is error prone
    • you might make a typo and not notice the mistake
    • maybe you test it differently every time, instead of being consistent
    • others cannot review the tests and see that testing is being done correctly
Avatar

Charles, thanks for writing that. It perfectly describes how I feel and what I've observed as a new Rails developer.

Avatar

one assertion per test makes sense

Can you explain why? It's not obvious to me.

Avatar

Hey Ryan, great screencast but I have one question. Say the user updates the value of the hidden field in the DOM for some weird reason (using inspect element). How can we account for this?

Avatar

Thanks for a great episode. You constantly amaze me with these ideas.

I think I found a small typo though. In /app/views/users/new.html.erb you have:

@user.errors.full_messages.each

I think you mean

@signup_form.errors.full_messages.each

Thanks again!

Avatar

If your calendar isn't showing up, make sure you use <%= calendar instead of <% calendar

<div id="articles">
<%= calendar do |date| %>
<%= date.day %>
<% end %>
</div>

Avatar

It is actually not that hard to do. I was worried about this step but the solution was straight forward.

ruby
        def current_tenant
                @current_tenant = User.find_by_alias_domain(request.host) unless %w(lvh.me other_domains_you_own.com).include?(request.domain)
                
                @current_tenant ||= User.find_by_subdomain!(request.subdomain) # includes(:home).
        end
        helper_method :current_tenant

Just remember to do this kind to double check every where you are checking for subdomain. Also you need to be shure your webserver (nginx for example) accepts all domains (this is the default if you have server by your self, do not know how this works on heroku)

Avatar

Instead of: match "controller#action"
Do: get "controller#action"

Avatar

Include the error messages in your YAML under activemodel, not activerecord.

For my LookupForm form object, I've got some YAML that looks like this:

ruby
en:
  activemodel:
    errors:
      models:
        lookup_form:
          attributes:
            plate:
              blank: "Needs a license plate"
            region:
              blank: "Needs a state"
Avatar

Thanks for this. Much more straight forward. I think you may have a typo at the very end though. This is what worked for me:

ruby
render "activities/#{activity.trackable_type.underscore}/#{activity.action}", activity.trackable_type.underscore.to_sym => activity.trackable
Avatar

html_safe is usually automatic. It's not generally necessary to call it explicitly. See http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/

Avatar

Actually, none of this is particularly correct. See my comment below regarding a way to do this without mixing JS, HTML, and Ruby.

Also, var foo = '&lt;foo&gt;' is actually the correct XHTML way of representing the JavaScript for var foo = '<foo>' (unless you're inside a CDATA section). The character entities are substituted before the JavaScript is evaluated. HTML, however, accepts < and > within a <script> element (which I didn't realize—I thought they were invalid, but http://validator.w3.org tells me that they are OK).

Avatar

I like the idea of Gon, but it mixes JavaScript into the generated HTML, and therefore is not advisable to use. The proper way to pass variables from Rails to JS is as follows:

ruby
# app/controllers/products_controller.rb
def index
  @products = Product.all
end
haml
/ app/views/products.html.haml
#products= @products.to_json
/ For simple values, you don't need to_json.
scss
// app/assets/stylesheets/application.css.scss
#products { display: none; }
javascript
// app/assets/javascripts/products.js
var products = JSON.parse($('#products'));

This way, your HTML output contains only HTML (JSON is simply text data, after all), and your JavaScript files contain only JavaScript. And that's the way it should be for separation of concerns (see also http://stackoverflow.com/a/7987959/109011 and http://stackoverflow.com/a/8819511/109011).

Avatar

Passing data to Javascripts through data attributes looks like an especially useful solution to my problem: I'm intending to use this technique to dynamically generate content for multiple popovers.

But I'm left with this question: how is the content file itself set up? As a partial in the same directory as layout referring to it?

Avatar

Hi Jasper, we're currently working on something very similar and trying to decide between using customer-specific schemas or using different tables. Do you mind sharing what you've done on your side and what were the pros/cons ? Much appreciated.

Avatar

Hey Jake,

Since we're doing it server-side, i think you should handle the case-insensitiveness on your code.

Looking at the example, we have a query

ruby
products = products.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")

What i did to fix this is use "ilike" instead of "like".
This way, we're doing a case insensitive like.

Hope this helps.

Avatar

I was getting the same thing. You have to sign out of that user and maybe delete the db record. You've updated some permissions and the token is now invalid. Once you do that and re-authenticate, you should be good. Worked for me.

Avatar

As I followed the tutorial, it return 'Can't mass-assign protected attributes: destroy' when I attempted to create the product type. How come ?

Avatar

Bingo! I ran into the same problem. Thanks!

Avatar

Check out smart_listing - our rails gem that makes easy to present data lists with built-in filtering, sorting and in-place editing.

Avatar

Hey Jorge,

You should be able to include cities if you had a "cities.csv" which matched the states structure.

To answer the other part of your question:

The "states.csv" and "countries.csv" data files are available in the github hosted "Source Code" under the "Show Notes" header:

https://github.com/railscasts/088-dynamic-select-menus-revised

By using the "db/seeds.rb" file you can migrate the data into any rails app.

bundle exec rake db:seeds

I hope this helps for future use.