Fan-Gated Facebook Tab with Rails 3 - ruby-on-rails-3

I followed a how to by CoverHound see
How to Create a Fan-gated Facebook Tab with Rails and JavaScript.
Everything went smooth up until step 3 under Serve the content for your FB App with a Rails application When previewing using my local server, I got an error. Typical rails security issue, simply solved by adding
protect_from_forgery :except => :index
to my FacebookController. From there I was golden, tested it on my live site and work swimmingly. Now to add the Gate!
Added the if statement to my facebook index.html.erb file
<% if user_likes_page? %>
<div class="fans_tickets"></div>
<% else %>
<div class="like_tickets"></div>
<% end %>
In the FacebookHelper I added the following to test for the like, and to parse the signed_request from Facebook
def user_likes_page?
fb_request = parse_signed_request
return fb_request['page']['liked'] if fb_request && fb_request['page']
end
def parse_signed_request
if params[:signed_request].present?
sig, payload = params[:signed_request].split('.')
payload += '=' * (4 - payload.length.modulo(4))
data = Base64.decode64(payload.tr('-_','+/'))
JSON.parse( data )
end
rescue Exception => e
Rails.logger.warn "!!! Error parsing signed_request"
Rails.logger.warn e.message
end
When tested on my localhost, It works great, if I haven't liked the page, I see the div with the info telling me to like the page for the contest info, when I have liked the page it shows me the info about the contests mentioned on the non-fan div. Great!
Post it to the Live server and I get an error page that shows up. In my Logs I see this...
2011-09-23 12:38:29 INFO -- Processing by FacebookController#index as HTML
2011-09-23 12:38:29 INFO -- Parameters: {"signed_request"=>"-IIMtqxxUICCyfCOxpsBMvApiaLgEZAkr1tQltvK_bI.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTMxNjgwMzEwNywicGFnZSI6eyJpZCI6IjEzNzg2NDQ2NjMxMDQwOSIsImxpa2VkIjp0cnVlLCJhZG1pbiI6dHJ1ZX0sInVzZXIiOnsiY291bnRyeSI6ImNhIiwibG9jYWxlIjoiZW5fVVMiLCJhZ2UiOnsibWluIjoyMX19fQ"}
2011-09-23 12:38:29 WARN -- !!! Error parsing signed_request
2011-09-23 12:38:29 WARN -- undefined method `encoding' for #<String:0x7f845221da58>
2011-09-23 12:38:29 INFO -- Rendered facebook/index.html.erb within /layouts/facebook (37.4ms)
2011-09-23 12:38:29 INFO -- Completed in 77ms
2011-09-23 12:38:29 FATAL --
ActionView::Template::Error (undefined method `[]' for true:TrueClass):
1: <% if user_likes_page? %>
2: <div class="fans_flames_tickets"></div>
3: <% else %>
4: <div class="like_flames_tickets"></div>
app/helpers/facebook_helper.rb:4:in `user_likes_page?'
app/views/facebook/index.html.erb:1:in `_app_views_facebook_index_html_erb___1213205873_70103145189880_0'
app/controllers/facebook_controller.rb:6:in `index'
I can't seem to figure out what would be causing this, the code doesn't look to be relying on anything from the actual server itself... Any help would be appreciated!
oh and I didn't continue on with the "How do I get the Facebook userID of the visitor viewing my fan page?" as I don't require it, its just for the like information.
UPDATE
Figured it out with debugging... should have been obvious. My Local host was implementing JSON with Guard running. With Guard only working in my development mode, JSON was installed on on development. Installed on Production and presto...
Feel kinda dumb for not having noticed this sooner! Thanks for all the help Dave & Keith

I'm pretty sure the undefined method 'encoding' for #<String... error has to do with running the app on ruby 1.8.7 vs. 1.9.2 or higher. i.e. it looks like your Live server is running 1.8.7 or possibly Ruby Enterprise Edition.
If you can, switch your live server to a ruby 1.9.2 version and see if that fixes it. Otherwise I'll dig in a little more this weekend.
Cheers!
-kw

Related

Rails 5 Minitest ActionView::Template::Error: nil is not a valid asset source

I upgraded my Rails Application from 4.2 -> 5.0.0.1.
Other TESTS works fine (e.g. Model, Helper, Feature), but havinf trouble with my Controller Test.
I have read about Keyword arguments in controller & integration tests in Rails 5. So I changed the code structure as given below...
ActionView::Template::Error: nil is not a valid asset source
setup do
#logo = plogos(:main_logo)
end
test "should get edit" do
puts #logo.id // just to check...working fine
get :edit, params: {id: #logo.id}
assert_response :success
end
But I got new error with ActionView.
Is there anyone encountered and fixed the same issue, please help!
Thank you!
You may want to add some logtrace, probably it hints you where it went wrong.
May it be that the main_logo-fixture doesn't have an image? Since Rails 5 image_tag raises this error when given an nil-value, see also: Rails, "nil is not a valid asset source" for a particular image_tag (Carrierwave)
Besides that, typically the new scaffolded code would look as follows:
require 'test_helper'
class LogosControllerTest < ActionDispatch::IntegrationTest
setup do
#logo = plogos(:main_logo)
end
#...
test "should get edit" do
get edit_logo_url(#logo)
assert_response :success
end
#...
end

Missing template with format js

In my rails project I want to open a modal box (face box) via ajax. My code in the index.html.erb:
<%= link_to 'Anmelden', fb_login_path, :remote => true %>
This throws me the error:
Missing template facebox/fb_login, application/fb_login with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :arb, :coffee]}. Searched in: ...
That is right because my template is a js.erb-file. I read somewhere that I have to add in my controller:
FaceboxController:
def fb_login
respond_to do | format |
format.js
end
end
Doing this I am getting the error:
Started GET "/facebox/fb_login" for 127.0.0.1 at 2014-11-05 18:09:46 +0100
Processing by FaceboxController#fb_login as HTML
Completed 406 Not Acceptable in 0ms (ActiveRecord: 0.0ms)
This is weird because last week everything worked. In the meantime - as far as I remember - I didn't change a thing. But now I am getting this error.
I know this sounds weird but I hope that someone can help me.
Thanks!
Lars
EDIT
This ist my fb_login.js.erb-Code:
$.facebox('<%= escape_javascript(render :partial => 'devise/sessions/new') %>')
EDIT 2
Here is the output for rake routes
fb_login /facebox/fb_login(.:format) facebox#fb_login
and routes.rb:
match '/facebox/fb_login' => 'facebox#fb_login', :as => :fb_login
Perhaps that helps
Setting 'rails' in the gem file to '3.2.20' and running 'bundle update rails' finally worked for me.

parameters are not passing to the controller Rails3 + coffeescript + ajax

I'm trying to implement a sorting list with Rails3 and coffeescript. I had a routing issue earlier and was able to solve it with your generous help, so now I have a different issue, My data parameter is not passing to the server,
Following is my view
#index.html.erb
<h1>Listing books</h1>
<ul id="books"> <% #books.each do |book| %>
<li class="book<%= book.id %>"><span class="handle">[drag]</span><%= book.name %></li>
<% end %></ul>
<%= link_to 'New book', new_book_path %>
following is my books.js.coffee file
jQuery ->
$('#books').sortable
axis: 'y'
handle: '.handle'
update: ->
$.post('/books/sort', $(this).data('#books'), $(this).sortable('serialize'))
Following is my controller
#books_controller.rb
def sort
#books = Book.all
#books.each do |book|
book.position = params['book'].index(book.id.to_s) + 1
book.save
end
render :nothing => true
end
this is the error I'm getting
Served asset /jquery.js - 304 Not Modified (0ms)
Started POST "/books/sort" for 127.0.0.1 at 2012-11-28 17:03:25 +0530
Processing by BooksController#sort as */*
Book Load (0.2ms) SELECT "books".* FROM "books"
Completed 500 Internal Server Error in 2ms
NoMethodError (undefined method `index' for nil:NilClass):
app/controllers/books_controller.rb:14:in `block in sort'
app/controllers/books_controller.rb:13:in `each'
app/controllers/books_controller.rb:13:in `sort'
Rendered /home/sameera/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/_trace.erb (40.8ms)
Rendered /home/sameera/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
Rendered /home/sameera/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (47.7ms)
So when i say p params, I get {"action"=>"sort", "controller"=>"books"}, So it doesnt have a param called 'book' and hence gives a nil error, can someone help me out,
any help will be greatly appreciated
thanks in advance
You have a couple things going wrong here. First of all, your $.post arguments are a bit confused:
$.post('/books/sort', $(this).data('#books'), $(this).sortable('serialize'))
$.post wants the data in the second argument so just this:
$.post('/books/sort', $(this).sortable('serialize'))
makes more sense.
Sortable's serialize method wants DOM id attributes to be in a specific form:
It works by default by looking at the id of each item in the format "setname_number", and it spits out a hash like "setname[]=number&setname[]=number".
In your Rails controller, you want an array of book IDs in params[:book] so you want book[]=id&book[]=id&... going to your server. That means that you want your <li>s to look more like this:
<li id="book_<%= book.id %>">
Or you could keep use class attributes by including an underscore:
<li class="book_<%= book.id %>">
and then telling serialize to look at class:
$(this).sortable('serialize', attribute: 'class')
You should also use the expression option and leave the HTML alone:
$(this).sortable('serialize', attribute: class, expression: /(book)(.+)/)
There are a few other ways to arrange things, see the sortable documentation for further details.

Memberships engine not working properly

I've installed RefineryCMS and a couple of its engines (like Blog). Everything was working fine until I installed Memberships engine.
After struggling a couple of days, I could make it "work". By "work" I mean that I could create a user, but since I have it installed, each time I access the home page I get the following error:
undefined method `refinery_user?'
Extracted source (around line #1):
1: <% if refinery_user? %>
2: <% unless admin? # all required JS included by backend. %>
3: <% content_for :stylesheets, stylesheet_link_tag('refinery/site_bar') unless !!local_assigns[:exclude_css] %>
4: <%= yield(:stylesheets) unless local_assigns[:head] or local_assigns[:exclude_css] %>
I've "ctrl+click" on that method and it does exist!! It has the following code:
def refinery_user?
user_signed_in? && current_user.has_role?(:refinery)
end
The weird thing is that I've put a breakpoint on that line but the app didn't stop there...
Does anybody know what's going on?
Make sure your /config/initializers/devise.rb file exists and that it includes the following (probably at the bottom):
config.router_name = :refinery

Troubleshooting empty params[] hash since Rails3 Upgrade

I have a named route that tests properly in the console and shows the :url_title which should be included in params[], yet params[] is always empty.
The question is, why is params[] empty? My expectation is it should have params[:url_title].
I also removed this route and used the default resource and params[] is still empty.
I've been checking params by using logger.
My app is an upgrade from Rails 2.3.5 to Rails 3.0.3.
Here's a code summary of what's going on.
# this is my route
match 'papers/:url_title' => 'papers#show', :as => :permalinkpaper
# this is link_to and the generated url being called
<%= link_to paper.title, paper_path(paper.url_title) %>
http://localhost:3000/papers/great-passion
# which properly matches to this controller#action for papers#show
def show
#paper = Paper.where(:url_title => params[:url_title]).first()
PaperHistory.add( current_user, #paper.id )
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #paper }
format.json { render :json => #paper }
format.mobile # { render :layout => false }
end
end
# which generals this error because the Paper looking returns noting because the params[:url_title] is nil
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
# the log stack trace
Started GET "/papers/great-passion" for 127.0.0.1 at Mon Jan 24 23:04:04 -0600 2011
Processing by PapersController#show as HTML
SQL (0.7ms) SHOW TABLES
SQL (0.5ms) SHOW TABLES
Paper Load (0.7ms) SELECT `papers`.* FROM `papers` WHERE (`papers`.`url_title` IS NULL) ORDER BY title LIMIT 1
Completed in 119ms
RuntimeError (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id):
app/controllers/papers_controller.rb:43:in `show'
# I've validated the route in the console and it seems to know :url_title is the proper value
>> r = ActionController::Routing::Routes
>> r.recognize_path "/papers/great-passion"
=> {:action=>"show", :url_title=>"great-passion", :controller=>"papers"}
UPDATE: I have found that params[] are NOT empty when values are in the URL, such as when performing a search.
http://localhost:3000/papers?utf8=%E2%9C%93&keywords=passion
This successfully produces
Started GET "/papers?utf8=%E2%9C%93&keywords=passion" for 127.0.0.1 at Tue Jan 25 00:20:07 -0600 2011
Processing by PapersController#index as HTML
Parameters: {"utf8"=>"✓", "keywords"=>"passion"}
params: utf8✓keywordspassion
Thanks to all for the help. I was able to disassemble my app piece by piece and finally get params[] to show up.
The culprit was the open_id_authentication plugin.
I had some plugins in the vendors directory, so I removed them all and after hurdling a few resulting errors (b/c the plugins were now missing) everything worked. I systematically replaced plugins, and when I got to open_id_authentication found that the params[] again disappeared.
I had a different solution for this problem that I'll post here just in case somebody runs into the same issue. I was working on a password reset part of the site and tried various things such as putting the URL in manually, specifying the controller and action, using a bare (minimal) form and such, but all of it failed. The error given was the e-mail parameter was blank.
A look into the Exceptional logs showed that not just the e-mail parameter was blank, but even the UTF-8 check mark was missing. The only things in the params hash were the controller and action. Reloading the page also didn't turn up the usual spiel about re-submitting information.
It turns out the problem was in SSL. The page was trying to use SSL but didn't have permission and it was somehow silently killing the form. Hope that helps somebody.