undefined local variable or method verify_recaptcha - ruby-on-rails

I am following the this to implement captcha, but I am stuck at last step. Here is my controller:
bug_report = BugReport.new(bug_report_params)
if verify_recaptcha
if bug_report.valid?
bug_report.save!
#render success
else
#throw error
end
else
#Invalid captcha
end
I am getting error saying: undefined local variable or method verify_recaptcha
Other codes are here:
view
<%= form_for :bug_report, url: bug_reports_path do |f| %>
<%= recaptcha_tags %>
<%= f.submit 'Submit' %>
<% end %>
gemfile
gem "recaptcha", :require => "recaptcha/rails"
recaptcha.rb
Recaptcha.configure do |config|
config.public_key = 'publik_key_here'
config.private_key = 'private_key_here'
end
I am getting the following data in params:
{
utf8: "✓",
g-recaptcha-response: "Long text here",
commit: "Submit",
controller: "api/v1/bug_reports",
action: "index"
}
Please guide me, how to fix it.

From your comments, It looks like you have the rails app with config.api_only = true set in application.rb. For a list of what it actually does, check this documentation.
One consequence of this is ApplicationController would inherit from ActionController::API instead of ActionController::Base. But if you look at recaptcha's source code, the include is on ActionController::Base.
So, you can directly include Recaptcha::Verify module in your ApplicationController.
# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
include Recaptcha::Verify
...
end

Related

undefined method - issues calling a helper method from a partial in a mail controller

I've set up an ActionMailer to email and pull a partial to post the data for the user, however the helper methods are comming back as undefined - i moved them to the application helper but still the same error, I think its in the way im passing the variable to the mailer ?
I've searched for same issue online but find that theres no concise response - I fear I'm doing something basic somwewhere wrong
Error:
undefined method `tidy_address' for #<#<Class:0x007f5c90681b10>:0x007f5c90ad8ba0>
My partial in order views : _enquiry_details.html.erb
<div class="row">
<div class="col-xs-2">
<h3><%= #customer.name %></h3>
<hr>
<h5><%= tidy_address(#customer.locations.first) %></h5>
<% #phone_number.each do |pn| %>
<h5><%= pn.name %> : <%=pn.phone_number.phone%></h5>
<% end %>
in my user mailer.rb
def lead_received(enquiry)
#order=enquiry
if #order.user
#customer=#order.user
else
#customer=#order.company
end
#locations=#customer.locations
#phone_number=#customer.phone_maps
mail to: "myemailaddress#domain.com", subject: "New Lead Received"
end
which I call with this passing the order , think this is where im going wrong
in order controller..
if #order.save
UserMailer.lead_received(#order).deliver_now
For clarity in my mailer view lead_received.html.erb
<%= render "orders/enquiry_details" %>
And finally in my locations helper
module LocationsHelper
def google_string(lat,long,size)
case size
when "s"
mysize="150x150&zoom=12"
when "m"
mysize="350x300&zoom=14"
when "l"
mysize="570x300&zoom=13&scale=2"
end
"https://maps.googleapis.com/maps/api/staticmap?"+URI.encode("markers=#{lat},#{long}&size=#{mysize}&key=AIzaSyAxRuThoVl-xziFElt3GPCESLsaye4_aGA")
end
# Return a sorted neat adress block
def tidy_address(location)
unless location.blank?
t_address=""
t_address="#{location.address1}<br>" if location.address1.present?
t_address=t_address+location.address2+"<br>" if location.address2.present?
t_address=t_address+location.address3+"<br>" if location.address3.present?
t_address=t_address+location.city+"<br>" if location.city.present?
t_address=t_address+location.postcode if location.postcode.present?
# t_address=t_address+"("+location.id.to_s+")"
#t_address=t_address+"<br><a href=''>Directions to here</a>"
t_address.html_safe
else
t_address="<link_to 'Add an address' '#'>".html_safe
end
end
end
Add the helper in the mailer code to use inside mailer.
class UserMailer < ActionMailer::Base
default from: "" # default from email
helper LocationsHelper
helper UserHelper
def lead_received(enquiry)
#order=enquiry
if #order.user
#customer=#order.user
else
#customer=#order.company
end
#locations=#customer.locations
#phone_number=#customer.phone_maps
mail to: "myemailaddress#domain.com", subject: "New Lead Received"
end
end

Ruby on rails can't create with params

I have a from created in Ruby on rails. The code the form looks like this:
<%= simple_form_for(#action) do |f|%>
<%= render 'shared/error_messages' %>
<%=f.label :action_name, "Action name"%>
<%=f.text_field :action_name%></br>
<%=f.input :startDate,:as => :datetime_picker, :label =>"Start date"%>
<%=f.input :endDate,:as => :datetime_picker, :label =>"End date"%>
<%=f.label :contentURL, "Content url"%>
<%=f.text_field :contentURL%></br>
<%= f.button :submit, class: "btn btn-large btn-primary" %>
<%end%>
But when I click the submit button I get this error:
undefined method `permit' for "create":String
def action_params
params.require(:action).permit(:action_name, :startDate,:endDate,:contentURL)
All other forms a working ok, I guess it is something really obvious, just can't see it :(
I really appreciate any help, solving this problem.
Thanks!!
EDIT:
Controller code:
def create
action = Action.new(action_params)
if #action.save
flash[:success] = "New Action saved"
redirect_to "/"
else
render 'new'
end
end
private
def action_params
params.require(:action).permit(:action_name, :startDate,:endDate,:contentURL)
end
In Rails 4, you must use Strong Parameters in your controllers. Here's some explanation from the official blog. And some example:
class PeopleController < ActionController::Base
# This will raise an ActiveModel::ForbiddenAttributes exception because it's using mass assignment
# without an explicit permit step.
def create
Person.create(params[:person])
end
# This will pass with flying colors as long as there's a person key in the parameters, otherwise
# it'll raise a ActionController::MissingParameter exception, which will get caught by
# ActionController::Base and turned into that 400 Bad Request reply.
def update
redirect_to current_account.people.find(params[:id]).tap do |person|
person.update_attributes!(person_params)
end
end
private
# Using a private method to encapsulate the permissible parameters is just a good pattern
# since you'll be able to reuse the same permit list between create and update. Also, you
# can specialize this method with per-user checking of permissible attributes.
def person_params
params.required(:person).permit(:name, :age)
end
end
Notice how, in the last lines, under the private keyword, the person_params method is defined, which declares the permitted fields to be assigned by the create and update methods on top. And it's the person_params that is used for updating - the valid example - instead of the raw params array.

Any suggestion for contact form rails 4

I am a newbie in Rails , trying to make a contact form for my app, but I can not catch the parameters that comes from contact form (like name and message) in Emailer class without asscociating a model. Any suggestion on that? Here are the list of classes and controllers.
My Emailer class is :
class Contact < ActionMailer::Base
default from: "from#example.com"
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
# en.contact.send_email.subject
def send_email(contact)
#greeting = "Hi"
mail to: "ostadfree#gmail.com"
end
end
Staticpages controller is :
def email_contact()
Contact.send_email().deliver
redirect_to contact_url
end
Contact.html.erb is include a form and two buttons at the end:
<%= submit_tag "Submit", class: "btn btn-large btn-primary" %>
<%= link_to 'Send Email', email_contact_path %>
and send_email.text.erb is :
Contact#send_email
<%= #greeting %>, find me in app/views/app/views/contact/send_email.text.erb
<%#= "Name :" + #name.to_s %>
Thanks.
Based on your code, you really don't have a grasp on how rails is designed to work. You're probably better off following a tutorial than getting a question like this answered here.
http://seanrucker.com/simple-ruby-on-rails-contact-form-using-activemodel-and-pony/
Try this:
in mailer:
def send_email(name,message)
#greeting = "Hi"
#name = name
#message = message
mail to: "ostadfree#gmail.com"
end
in controller:
def email_contact()
Contact.send_email(params[:name],params[:message]).deliver
redirect_to contact_url
end
where name and message - names of form's fields. If it sent a mails before, that code should work.
Anyway, check it, really: http://guides.rubyonrails.org/action_controller_overview.html#parameters

Rails gem acts_as_follower create/destroy error: Couldn't find Member(user) with id="username"

I'm setting up a follow system with the Rails Gem acts_as_follower and I've run into a problem I'm not sure how to fix.
When I go to follow for example a user with the username of 'testuser1' I get this error:
Couldn't find Member with id=testuser1
app/controllers/follows_controller.rb:6:in `create'
Parameters:
{"_method"=>"post",
"authenticity_token"=>"FnqLCCQYcFGMerOB56/G6dlPvzpPhPDFbxCXaiDBOUU=",
"member_id"=>"testuser1"}
Here's my Controller:
class FollowsController < ApplicationController
before_filter :authenticate_member!
def create
#member = Member.find(params[:member_id])
current_member.follow(#member)
end
def destroy
#member = Member.find(params[:member_id])
current_member.stop_following(#member)
end
end
The form to create the follow:
<%= link_to("Follow", member_follows_path(member.to_param), :method => :post, :class => "btn") %>
<%= link_to("Following", member_follow_path(member.to_param, current_member.get_follow(member).id), :method => :delete, :class => "btn btn-follow") %>
And this is how I've defined my to_param since that's how you get to a member/user's page:
def to_param
user_name
end
Anyone out there know how I can go about fixing this? Thanks.
Remove the to_param. When you're using the URL helpers, such as your member_follows_path, you need to pass the ID, or from the ERB's perspective, the object itself (it'll resolve to the ID when the ERB renders)
Alternatively, in your rails controller, change the find to something like find_by_user_name, or whatever the field is supposed to be, and then that line should work. Beware that this will be slower, especially if you have a large database without proper indexing / partitioning.

rack-affiliates gem with localhost

I'm messing with Rack::Affiliates but I don't know if it works with the domain localhost in development environment.
1º This is my config in application.rb file:
config.middleware.use Rack::Affiliates, {:param => 'aff_id', :ttl => 6.months, :domain => '.localhost'}
2º I send a email with a link and param aff_id something like:
<%= link_to "accept invite", new_user_registration_url(:aff_id => #user.id) %>
3º In root action:
def index
if request.env['affiliate.tag'] && affiliate = User.find_by_affiliate_tag(request.env['affiliate.tag'])
logger.info "Halo, referral! You've been referred here by #{affiliate.name} from #{request.env['affiliate.from']} # #{Time.at(env['affiliate.time'])}"
else
logger.info "We're glad you found us on your own!"
end
respond_to do |format|
format.html
end
end
I'm getting the message on console:
We're glad you found us on your own!
What am I doing wrong?
Thanks!
Did you remember to include config.middleware.use Rack::Affiliates in your config/application.rb file?
If not, add it and see what happens.
Otherwise you can try debugging by changing the if statement to:
if request.env['affiliate.tag']
logger.info "request.env['affiliate.tag'] = #{request.env['affiliate.tag']}"
else
logger.info "We're glad you found us on your own!"
end
This should tell you if the affiliate.tag is getting set and if so to what value.
It's all due to User.find_by_affiliate_tag. have you any column named affiliate_tag.
If your are inviting using this link <%= link_to "accept invite", new_user_registration_url(:aff_id => #user.id) %> where you are using #user.id as aff_id.
So you have to use User.find_by_id instead of User.find_by_affiliate_tag
Final code snippet of exmaple contoller will look like
class ExampleController < ApplicationController
def index
str = if request.env['affiliate.tag'] && affiliate = User.find_by_id(request.env['affiliate.tag'])
"Halo, referral! You've been referred here by #{affiliate.name} from #{request.env['affiliate.from']} # #{Time.at(env['affiliate.time'])}"
else
"We're glad you found us on your own!"
end
render :text => str
end
end

Resources