RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

I'm wondering, what would be a good meganism to ensure the user received the message? Im sure in some cases its important that the application is aware that the user received the message.

Probably not with a hidden form or something.

Avatar

Thanks for your reply. Already tried the constraints but it didn't work out.

Avatar

This functionality was added after the last gem release 0.12.0, if you want to use the latest release you can use the github version by adding the following in your Gemfile:

ruby
gem "prawn", :git => "git://github.com/sandal/prawn.git"
Avatar
  # Subdomain / client application
  constraints(:subdomain => /.+/) do
    root :to => 'blog#show'
  end
  
  # No subdomain / root application
  constraints(:subdomain => /^(|www)$/) do
    resources :blogs
  end
Avatar

Hi,
i'm trying to extend this example with json response
in session controller

def create
auth = request.env["omniauth.auth"]
user = User.where(:provider => auth['provider'],
:uid => auth['uid']).first || User.create_with_omniauth(auth)
session[:user_id] = user.id
respond_to do |format|
format.html { redirect_to root_url, :notice => 'Signed in!'}
format.json { render :json => user }
end
end

Started POST "/auth/identity/callback.json"
i got error 500

NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]):
app/controllers/sessions_controller.rb:10:in `create'

coresponding with this code in the session create controller

user = User.where(:provider => auth['provider'], 
                  :uid => auth['uid']).first || User.create_with_omniauth(auth)

How to add json response in this schema?
i need able authorize to my site via mobile app

Avatar

davodesign84,

Have a look here: http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:signin_upon_signup

Hartl doesn't use has_secure_password. But I think you can use same logic when implementing that feature.

Avatar

Same here. Exactly what I expect from Pro episodes. The full cycle with cancellation, changing plans and insufficient funds would be awesome. Thanks Ryan! (also waiting for PayPal implementation on Railscasts :)

Avatar

check the runtime dependencies in http://rubygems.org prior to starting any feature addition ....

for example... http://rubygems.org/gems/best_in_place best_in_place requires Rails ~> 3.1.0 ....

Avatar

yes, google for webmasters allows you to see a count estimate of the any related topic you may be watching,,, it was created as a tool for SEO but i guess you could use it that way too...

but this time I think you were just lucky :D

Avatar

maybe some modifications to the js are needed... out of my head I can think of including the label on the :onclick event that triggers the edition...

or maybe changing the empty value to something like "none"

Avatar

read my post from up here,,, maybe that will help...

Avatar

well... you could change your whole edit action view to look exactly the same as your show, so the user gets that feeling that he/she is editing the thing directly....

this could be activated by some nice button that says "Activate edit mode" (which also warns that the changes are instantly saved)

and at the bottom of the page (or wherever it fits) another button saying "Finished with my edits" , which redirects to show view...

this way you would cut down on requests that aren't made precisely to edit (some user randomly clicking your UI... happens....)

Avatar

Ryan says "when I un-focus" so it doesn't seem that Enter are required for the editions to take place,,, guess the best-in-place js s take care of that

I was asking the a similar thing myself: "what if I want to have a carriage return in the middle of batman's bio ???"

Avatar

I'm trying to set up this and use rspec integration tests and I thank you for this, but isn't this always going to pass when testing?

``` sessions_spec.rb
describe "Login" do
before do
@user = Factory(:user)
ApplicationController.stub(:current_user).and_return(@user)
end

it "should allow a valid user to log in" do
  # visit new_session_path
  # fill_in 'Email', :with => @user.email
  # fill_in 'Password', :with => @user.password

  # click_button 'Login'
  # current_path.should == root_path
  # page.should have_content "Logged in"
  page.driver.post sessions_path, :user => {:email => @user.email, :password => @user.password }
  ApplicationController.current_user.should_not be_nil
end

```

Avatar

What you can do is set config.rollout in your env file and then use App::Application.config.rollout.

For something more elaborated like App::Application.rollout?, you can create your own mixin and have method_missing verifying the actual variable.

Avatar

I do not work the path "/auth/google_apps" on the form, change it to "/auth/google_oauth2" and works great!!

Avatar

yeah, I was thinking the same... There is an advantage of using rbenv instead of rvm in a production environment? perhaps it's something about performance

Avatar

Another great screencast.

I've implemented this auth_token into an app that uses simple omniauth (#241) for authentication. Is this auth_token the same token I could use for a user to call my app's API or do I need to generate a different token for that purpose?

Avatar

Helped me overcome a seemingly difficult situation. The inverse_relationship helped a lot.
Thanks!

Avatar

We bundled together premailer with some Mailchimp templates at Sandglaz and use that for our newletters. It is published as the Maktoub gem at https://github.com/Sandglaz/maktoub.

Contributions and improvements are welcome.

Avatar

Quick question,

I have all of this working like a charm. However is not clear how I can call the login and what parameters it takes.
For example I would like the use to be signed in when on successful signup.
How can I do it?

Thanks :)

Avatar

That also crossed my mind, but in this case it basically adds complexity. Instead of a Rails.env.demo?, I would have a rollout? helper call and an overhead through the feature set management (the demo-abilities won't change over time)

I've also thought of a custom form builder to shrink down the view overhead—but then I still need a comfortable way to define the accessibility restrictions…

—Dominik

Avatar

Found an example in a github issue of a nginx config: https://github.com/ryanb/private_pub/issues/18

Avatar

Is there a way to not have all other routes respond to the subdomain and viceversa? Since now that same content would get served on two urls and considered duplicated by search engines.

update: I've been doing some research but nothing found, I'm using a basic redirection depending on controller_name and request.subdomain in a before_filter in application_controller

Avatar

Has anyone been successful with an nginx frontend to a faye server? I know it's a little tricky with websockets (because nginx talks HTTP 1.0 with the backend), but I was wondering about faye.

Avatar

I'd love to see a take on this that removes Mailman from the equation and handles emails that are "delivered" to the app via a POST request (a la Sendgrid's Post API).

Avatar

I run in such problem, that i have a validation in task model of presence project_id,
Solution was: tasks.build(attributes.merge(:project_id => self), to merge attributes array with project_id.
I wonder is there a better solution to do this?
and why "tasks.build" in project model doesn't build this relation?
I am using Rails3, ruby 1.9.2

Avatar

I think to merge arrays of different model values

Avatar

Is there a convenient way to separate view and controller logic depending on the environment? I have, for example, a "demo" environment which limits some of the functionality of the app. In result, I have many snippets like

ruby
# in a view
<% if Rails.env.demo? %>
  <dt>Amount (fixed in demo)</dt>
  <dd>2</dd>
<% else %>
  <dt><%= f.label :amount %></dt>
  <dd><%= f.text_field :amount %></dd>
<% end %>

and a corresponding conditional in the controller (+ some modified models – but I don't think, there is a way around different behavior, is it?), which is some kind of messy, especially if only some fields are going to be unchangeable in the demo environment.

Maybe CanCan 2.0 could be a solution, since then the "demo abilities" are more or less centralized... But: would that be the right way?

—Dominik

Avatar

Ryan, for this one, I really wish you had included some info on how to test.

Avatar

Same issue, has this been fixed? thanks.

Avatar

Let's say you wanted to add sort order to the results in my comment above, then you could do this:

models/project.rb
def self.search(search)
  if search
    where('name LIKE ?', "%#{search}%").order('created_at DESC')
  else
    order('created_at DESC') # note: default is all, just sorted
  end
end

And then you could refactor like this:

models/project.rb
def self.search(search)
  arel = order('created_at DESC') # note: default is all, just sorted
  arel = arel.where('name LIKE ?', "%#{search}%").order('created_at DESC') if search.present?
  arel
end

And if you also wanted to search description you might do this:

models/project.rb
def self.search(search)
  arel = order('created_at DESC') # note: default is all, just sorted
  arel = arel.where('name LIKE ? OR description LIKE ?', "%#{search}%", "%#{search}%").order('created_at DESC') if search.present?
  arel
end

Next, change your controller to pass the whole params rather than just params[:search]):

projects_controller.rb
def index
  @projects = Project.search(params)
end

Then update your search method accordingly:

models/project.rb
def self.search(params)
  arel = order('created_at DESC') # note: default is all, just sorted
  arel = arel.where('name LIKE ? OR description LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%").order('created_at DESC') if params[:search].present?
  arel
end

Why do all this? Because if you had more fields in your search view, you could easily search them too! For instance, let's say you change the above view to also include min price and max price:

projects/index.html.erb
<% form_tag projects_path, :method => 'get' do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= text_field_tag :min_price, params[:min_price] %>
    <%= text_field_tag :max_price, params[:max_price] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

Then in the search method, you do:

models/project.rb
def self.search(params)
  arel = order('created_at DESC') # note: default is all, just sorted
  arel = arel.where('name LIKE ? OR description LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%").order('created_at DESC') if params[:search].present?
  arel = arel.where('price >= ?', params[:min_price]) if params[:min_price].present?
  arel = arel.where('price <= ?', params[:max_price]) if params[:max_price].present?
  arel
end

And for style you could change your view to use search_field_tag, size, and placeholder:

projects/index.html.erb
<% form_tag projects_path, :method => 'get' do %>
  <p>
    <%= search_field_tag :search, params[:search],  size: 20, placeholder: 'keywords' %>
    <%= search_field_tag :min_price, params[:min_price], size: 12, placeholder: 'min. price' %>
    <%= search_field_tag :max_price, params[:max_price], size: 12, placeholder: 'max. price' %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

I hope this helps someone. For more info, see: http://railscasts.com/episodes/111-advanced-search-form-revised

Avatar

Maybe a CollectionPresenter that delegates the finer details to the instance presenter. You could even make it a base class, and subclass it with UserCollectionPresenter, etc. depending on how diverse your views are.

Avatar

Please copy/paste the controller's index action, and the model's search method.

Avatar

For Rails 3 compatibility, the ActiveRecord queries in the search method should look like this:

models/project.rb
  def self.search(search)
    if search
      where('name LIKE ?', "%#{search}%")
    else
      all
    end
  end

See http://railscasts.com/episodes/202-active-record-queries-in-rails-3 and http://m.onkey.org/active-record-query-interface

Avatar

This is due to a Rails 3 change:

Helpers like form_for or div_for that insert content from a block use <%= now

See "7.4.2 Helpers with Blocks" in http://edgeguides.rubyonrails.org/3_0_release_notes.html

Avatar

Anyone know how to use this to convert a search into a zip code?

Avatar

I do not why, but only
$(link).prev("input[type=hidden]").val("1");

worked for me in a case of the jquery remove_fields(link) function and rails 3.1.3.

Avatar

To clarify what I meant by in the same order above.

It always will select the same users for tests in the same order (as you ramp up that is -- so if you always run your tests at 20% the same 20% of your site users will be effected).

Ah one last thing is this sort of implementation requires you to be only testing users. So you wouldn't be able to split run a feature on your homepage across all visitors. That may not matter in most cases since you likely can get a feel if it works from users but, for example, if you wanted to test a new sign up form or sign up text to entice users you'd be out of luck.

Avatar

I like the custom implementation but it could use some work in regards to the percentage selection.

def match_percentage?(user)
percentage ? user.id % 100 < percentage : true
end

It always will select the same users for tests in the same order.

So if you're running multiple tests you have an almost certain chance the same customers will be in each of the same tests.

It'd be better to just randomly pick users (using the percentage as a means to select them) and then sticky session them some way (perhaps a cookie with which features values you're currently opted into) to keep them in the select group. Then you could analyze the results from the tests independently of each other without having them always intersect.

On top of that if you went with the current approach and tended to have multiple faulty features you're subjecting the same users always to these features. If I was always part of the 1% that has features tested upon it I'd likely be annoyed if most of the rollouts were painful as my perception of the site would be degraded. Having it more random will prevent certain users from being the guinea pigs of the lot.

Just a thought but definitely agree having a custom one may be better than having all the extra dependencies.

May be worth it to eventually build out a gem that handles some intense feature testing (alt controls to stabilize populations, quick reporting, feature value touched to determine whether the feature was touched or not by the user, multiple test features for a test, etc) but that's likely outside the scope of this.

Either way, keep up the good work man, enjoying learning Rails through these casts.

Avatar

I'm having an issue getting font color to work. I have the code below in my OrderPdf class I recieve no errors but it never changes the color, any ideas?

ruby
text "#{@agenda.customer.name.titleize} - Weekly Conference Call", :align => :center, :size => 25, style: :bold, :color => "0000FF"
Avatar

I keep getting WARNING: Can't verify CSRF token authenticity when submeting a form from the root domain (domain.com) to a subdomain (example.domain.com). I found a way to share the cookies in all subdomains (domain: :all in session_store.rb), but i can't found a way to share the token. Anyone can help me?

Avatar

I've been fine testing Faye with Cucumber in a single browser session but as soon as one of my features spins up a second browser and starts testing the interaction between the two WebDriver hangs and times out. It's definitely Faye, probably the WebSocket connection, causing the issue. I have not found a work around. Not much information out there about it unfortunately.

Avatar

Dev works fine, production is the problem.

I get no such file to load -- rubygems

I suspect the delayed_job file. Should I change the delayed_job script file in any way? my production is bundled with rails 3.0.11 and ruby 1.8.7p352.

I tried which ruby and then changed the first line of the delayed_job, but then I get permission problem. I also tried chmod 755 on the which ruby path. any ideas?

I can not change to 1.9.2 ruby, because of some older apps there.

Avatar

Great cast!

Dosen't work on windows however, as the hiredis gem fails to bundle as the config, compiler and make fails since it cannot find /sys/socket.h.

Anybody tried changing the #include stmt to use winsock.h or winsock2.h???

BR

Rutger