RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

Hi. I'm using this in Rails 4 and I have params like so:

def user_params
params.require(:user).permit(:email, :password_hash, :password_salt, :password)
end

Is it ok to put :password into params here? The code doesn't work (doesn't save) without it. Should be ok since "password" is not in database, but I'd like a confirmation.

Avatar

I was able to fix the ExecJS error. Had to do with having spaces instead of tabs in my coffeescript function.

Avatar

Just an fyi, for ruby 2.0 the syntax for the pick_winner task is User.order('random()').first (vs. User.find(:first, :order => 'random()')

Avatar

Great screencast, thanks Ryan.

Currently requirements for a markup are different from what is described in the screencast. Check the source code of the official demo page http://jejacks0n.github.io/mercury/

html
<div id="hero_content" contenteditable="true" style="overflow: auto;" data-mercury="full">
    <h1>Mercury Editor</h1>
</div>
Avatar

If you're using a mountable engine, here's the best way to get the commentable working:

In your routes.rb:

resources :questions do
        resources :comments, :defaults => { :commentable => 'question' }
end

resources :answers do
        resources :comments, :defaults => { :commentable => 'answer' }
end

In your comments_controller.rb:

module MyEngine
  class CommentsController < ApplicationController
          before_action :load_commentable

  private

          def load_commentable
            @commentable = MyEngine::const_get(params[:commentable].classify).find(commentable_id)
          end

          def commentable_id
            params[(params[:commentable].singularize + "_id").to_sym]
          end

  end
end

For mountable engines, you HAVE to do MyEngine:: when constantizing the object. Won't work without it.

Avatar

George, thanks. I just ran into that problem.

Avatar

Fairly simple to achieve.

Assuming your Player model has_many :salaries, you can enable the expected f.fields_for :salaries behaviour in your form by adding the appropriate attributes:

ruby
class PlayersForm
  include ActiveModel::Model

  def persisted?
    false
  end

  attr_accessor :salaries, :salaries_attributes

  def initialize(player)
    @player = player
    @salaries = player.salaries
  end
end
Avatar

Adding:

coffeescript
$('#new_entry')[0].reset()

into my entries_index.js.coffee file under createEntry causes an

ExecJS::RuntimeError in Main#index
SyntaxError: unexpected CALL_START
  (in /Users/lionelramos/Documents/raffler/app/assets/javascripts/views/entries/entries_index.js.coffee)

My log has this:

coffescript
ActionView::Template::Error (SyntaxError: unexpected JS
  (in /Users/lionelramos/Documents/raffler/app/assets/javascripts/views/entries/entries_index.js.coffee)):

Any thoughts?

Avatar

Yep, it was due to calling the create_activity method after the object had been destroyed.

According to the gem maintainers, you simply have to assume the record will be destroyed, and call create_activity before the destroy

Avatar

Did you manage to implement this?

Avatar

Okay - so this railscasts is very useful, however I have a scenario that I need help with. Say I just want to create a Task list with no associated Task List/Project Name. So I have only one model and want the user to be able to enter multiple Tasks as they wish. How would I go about doing so?

Avatar

try to format it like this
when ".csv" then Roo::Csv.new(file.path)

this is the rubydoc for roo
http://rubydoc.info/gems/roo/frames

Avatar

Did anyone find a workaround for the arrange method in Ruby 1.8.7?

I am trying to enhance a few features within a two year old Rails application. Would greatly appreciate any ideas.

Avatar

I keep getting the same error: wrong number of arguments (3 for 2). Did you end up finding a solution to this?

Avatar

Excellent tutorial Ryan as usual .Thank you very much. Just an idea for future episode - how to allow user to top up his in-site account using Stripe/Paypal and activate/deactivate services provided based on the account balance.

Avatar

I need to scroll to the bottom of the comments more often. I forget they are organized oddly.

Avatar

For version 0.9 and above, the json_for should change from:

target.active_model_serializer.new(target, options).to_json

to

ActiveModel::Serializer.serializer_for(target).new(target, options).to_json

Avatar

I'm surprised there were no comments about issues with adding an entry. This took me sometime to figure out so posing here.

I was getting a 500 error when trying to add a name entry:

Completed 500 Internal Server Error in 1ms

ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):
  app/controllers/entries_controller.rb:13:in `create'

I guess in rails 4 some extra parameter requirements are needed:
more info here:
http://stackoverflow.com/questions/17868427/rails-4-activemodelforbiddenattributeserror
http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

Here's my implementation of the fix. Let me know if I overlooked something and this is not really needed please!

In entries_controller.rb

ruby
class EntriesController < ApplicationController
  respond_to :json
  
  def index
    respond_with Entry.all
  end
  
  def show
    respond_with Entry.find(params[:id])
  end
  
  def create
    respond_with Entry.create(entry_params)
  end
  
  def update
    respond_with Entry.update(params[:id], params[:entry])
  end
  
  def destroy
    respond_with Entry.destroy(params[:id])
  end

  private
    # permissible attributes.
    def entry_params
      params.require(:entry).permit(:name)
    end

end
Avatar

Uhg... spent so much time trying to figure this out ... THANKS!

I am new to rails/backbone so it was pretty confusing.

Avatar

I have the same question...does anyone know the answer?

Avatar

Disagree. I don't watch these to be entertained, and to really do a fair apples-to-apples comparison with backbone and angular, we have to see the same app being built with them all. It's the only way to really understand the different approaches, and how much code/work/learning each takes to accomplish the same thing.

Avatar

Thanks for the video. It's awesome.

Is is possible to store the json output as variable value, apart from displaying it in a view?

Avatar

Now that there's HTML5 Server-Sent Events, should one still use Faye?

(See how Juggernaut was 'depreciated' )

Avatar

Hello!

This works great!
How can i add to the search query a second variable from the same model?

i used

def self.search(query)
where("title like ?", "%#{query}%")
end

but i also have a little description (post.description) in the index view and i want to add it to the search query.

Ty very much

Avatar

Note that authenticate_or_request_with_http_token will return 401 messages as text/html- not what you want for a JSON API.

I handled this by overriding request_http_token_authentication in the controller:

ruby
def request_http_token_authentication(realm = "Application")  
  self.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
  self.__send__ :render, :json => { :error => "HTTP Token: Access denied. You did not provide an valid API key." }.to_json, :status => :unauthorized
end
Avatar

@coredevs did you find an answer for this question? I ran into the same issue. Thanks =)

Avatar

Hi Ryan,

I keep getting this error:

{
"error": {
"message": "Error validating application. Invalid application ID.",
"type": "OAuthException",
"code": 101
}
}

The FB application ID matches the one that was given to me...so I don't really know what's up.

Before I watched the Railscast, I actually followed directions from: https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview

Here's a link to my repo: https://github.com/margotungsten/splurgeorsave

Could you help?

Thanks!

Avatar

@Charlie, were you able to get your issue to work, regarding "No File Chosen"? I'm trying to have that text hidden until a file is uploaded.

Avatar

Is there a way to get "No File Chosen" to stay hidden, until the user uploads a file? I'm using Simple_Form and Paperclip in my app. Tried some examples on StackOverflow but none them worked out.

Avatar

If someone is in trouble with an "undefined method error" to capybara, just try to rename the requests folder to features.
Hope it help someone.

https://github.com/rspec/rspec-rails/issues/360

Avatar

Thanks! This worked, though still don't understand why.

Avatar

Where is the data in states.csv sourced from?

Avatar

I agree with Tony, I like these walkthroughs, learn a lot on in and out of Rails. Actually I rather have video where we talk about smaller sections instead of a large topic of view/controller walkthrough it's just too much information crammed into a short video

Avatar

I noticed that in 404 cases the ExceptionWrapper somehow returned 500 (not sure why). When really an exception occured, it would however render a 404 instead of a 500.

In stead of my previous comment, I have used:

ruby
status = params[:status] || ActionDispatch::ExceptionWrapper.new(env, @exception).status_code

Also, I figured that simply creating static error pages (even from PROD environment) is not sufficient in Rails 4. The whole reason I am using dynamic pages is because the assets no longer are offered in a non-digest way. Therefor I cannot generate static pages and commit them, as the digest will change per deploy on prod (precompiling assets everytime). A github issue (https://github.com/rails/sprockets-rails/issues/49) has been made a while back about this.

It would be nice if Ryan could elaborate/update this screencast about this issue.

Avatar

Tried in Rails 4, works fine. Except calling directly to errors/404 (for using the curl stuff). However Mike Henke pointed to the correct solution, at least in Rails 4 I had to remove the action: part. After that it worked fine. Including the status passing it would be:

ruby
def show
  status_code = ActionDispatch::ExceptionWrapper.new(env, @exception).status_code
  render request.path[1..-1], status: status_code
end

Also, just using the dynamic pages would result in my feature specs into a ActionView::MissingTemplate error. Even with config.consider_all_requests_local = false in the test.rb within the environments folder.

The only thing that helped me so far was to create static error pages using the (now working) curl command.

Avatar

match isn't deprecated in Rails 4; you just have to specify the HTTP method:

ruby
# Rails 3.2
match "/users/:id" => "users#show"

# Rails 4.0
match "/users/:id" => "users#show", via: :get
# or equivalently
get "/users/:id" => "users#show"

match is still useful for paths that respond to multiple HTTP methods.

Avatar

hi! has someone make this work with rails 4 and capistrano 3.0?

Avatar

After doing the exercise again, I can pin the above error to whitespace issues.
It seem that the scaffolding generated in the view file indents with spaces. I was indenting with tabs. When I changed all indentation throughout the file to tabs I could follow the same indentation as the screencast.

Avatar

I'm new to CoffeeScript.

I couldn't get the template to render. This fixed it:
In entries_index.js.coffee, render: -> had to be indented 1 level in from template: JST['entries/index'].

In the ascii cast, they appear to be on the same level of indentation.

Hope this is of help to someone.

Avatar

the .make is a method is a method from the machinist gem, just saying...

Avatar

Solved, by adding the aoColumns to jquery, but sort and search functions don't work

Avatar

Hi ericeche,

I'm looking for apply your solution, but JSON data format changes.
Before record was as:
["December 18, 2013","Forniture",......,"\u003Ca class=\"btn btn-mini\" href=\"/userfeedbacks/11\"\u003EShow\u003C/a\u003E"
Now I have something like that:
[{"created_at":"December 18, 2013","product":"Forniture",....]

I don't understand how to convert it and how I can add some action buttons as in the previous example.

Many thanks

Avatar

This is not thread-safe at all. Mutating static scope is never threadsafe.

When asking what is thread-safe and what isn't it also depends on your application. In generall mutating shared state without a mutex, semaphore etc. is not threadsafe.

For Rails you have a seperate controller instance per web request thread. So mutating
controller instance vars and all the instance vars of the objects created by controllers is threadsafe, whereby mutating statics is not, because it is shared among all threads.

Rubyists hack around this with the Thread.current Hash

Avatar

You can get the requested version using version_name method, so you can just add to the name of the default file name