I am relatively new in Ruby on Rails programming, and I got this error when trying to use the mail_form gem.
The error is in the create function as can be seen
I think I got all setup the correct way:
My model is like this:
class Contact < MailForm::Base
attribute :name, :validate => :true
attribute :email, :validate => /\A([\w\.%\+\-]+)#([\w\-]+\.)+([\w]{2,})\z/i
attribute :message, :validate => :true
attribute :nickname, :captcha => :true
def headers
{
:subject => "Contact Form",
:to => "(my email)",
:from => %("#{name}" <#{email}>)
}
end
end
I don't know if matters that I'm trying to create a site with only one page, so I have the form to create a new contact in the welcome.html.erb of the pages controller, but I am defining the contact:
def welcome
#admin = Admin.find(1)
#projects = Project.all.order('created_at DESC')
#contact = Contact.new
end
Also I think that matters, that the create function (that is throwing the error) is in the contacts controller, I don't know if there was ok or it will be better at the same controller as the Contact.new (in the welcome function of pages):
def create
#contact = Contact.new(params[:contact])
#contact.request = request
if #contact.deliver
redirect_to(root_path, :notice => "Thank you for contacting me. I will reply shortly!")
else
flash.now[:error] = 'Cannot send message.'
end
end
I haven't tested in production yet, only in development maybe this won't happen in production, but I want to know why is this happening to me because I am following a tutorial of Mackenzie Child and this didn't happen to him, and we have the same code(except for the fact that I am trying to make this in only one view). I don't know if it helps, but this is what I have in my config/environments/development.rb:
config.action_mailer.delivery_method = :letter_opener
So in development I'm using the gem letter_opener for displaying the messages instead of sending mails, although this affects nothing in the error because the error was showing up way before I installed the gem.
I have searched in many places and in all the questions on stack overflow but I found nothing. If you can help me that would be grate.
Thanks.
EDIT:
I have tested in production with heroku and returns the same error :(
Ok,
I asked in the gem's github page and I could resolve the issue. It was that in the validation of the attributes on the Contact model I was declaring the :true as an object when it has to be only a boolean true (without colon before). Good to know for avoiding silly mistakes.
Related
I'm trying to install the contact page on my Ruby on Rails app. It seems straight forward enough, but after installing the mailer gems, and creating my controller with:
$ rails generate controller contact_form new create
I navigate to my contact URL (/contact_form/new), and it says
"Unable to autoload constant ContactFormController, expected
/home/ubuntu/workspace/app/controllers/contact_form_controller.rb to
define it"
Routes and controller are as follows:
routes.rb
get 'contact_form/new'
get 'contact_form/create'
resources :contact_forms
contact_form_controller.rb
class ContactFormsController < ApplicationController
def new
#contact_form = ContactForm.new
end
def create
begin
#contact_form = ContactForm.new(params[:contact_form])
#contact_form.request = request
if #contact_form.deliver
flash.now[:notice] = 'Thank you for your message!'
else
render :new
end
rescue ScriptError
flash[:error] = 'Sorry, this message appears to be spam and was not delivered.'
end
end
end
contact_form.rb
class ContactForm < MailForm::Base
attribute :name, :validate => true
attribute :email, :validate => /\A([\w\.%\+\-]+)#([\w\-]+\.)+([\w]{2,})\z/i
attribute :message
attribute :nickname, :captcha => true
# Declare the e-mail headers. It accepts anything the mail method
# in ActionMailer accepts.
def headers
{
:subject => "My Contact Form",
:to => "your_email#example.org",
:from => %("#{name}" <#{email}>)
}
end
end
Note that your class is named ContactFormsController and Rails is looking for ContactFormController. You need to pay careful attention to the pluralization in Rails.
Controllers are plural.
Models are singular.
Routes are plural in most cases.
The pluralization of classes must always match the file name.
So why is Rails looking for ContactFormController? Because your routes are not defined properly:
get 'contact_form/new'
get 'contact_form/create'
get 'contact_forms/new' is the proper route for a form to create a new resource. You don't create resources with GET so get rid of get 'contact_form/create'.
resources :contact_forms
Is actually all that you need.
So to fix this error you should:
rename contact_form_controller.rb -> contact_forms_controller.rb.
change your route definition.
request /contact_forms/new instead.
I'm new to Rails and have been writing a simple app to post to Tumblr. I got all my oauth stuff working, and decided to use the tumblr_client gem to facilitate posting. I can get it to post just fine through the console, but the same code does not do anything in the controller. It doesn't throw any errors, it just does nothing. Any suggestions? (I censored the blog with {blogname}, but it is correct in my code)
def post
#user = Tumblog.find_by_user_id(5)
#client = Tumblr::Client.new(:consumer_key => #key, :consumer_secret => #secret, :oauth_token => #user.oauth_token, :oauth_token_secret => #user.oauth_secret)
#client.text("{blogname}.tumblr.com", :body => "test", :state => "draft")
redirect_to "http://www.tumblr.com/blog/{blogname}/drafts"
end
It turns out that it was a conflict with my instance variable name. Changed #client to #clients and it worked just fine.
I'd like to add a custom filter field to "Add News" page in Redmine,
so that when I add a new news I could select group of users the email should be sent to.
The field itself is a list of Redmine User groups and every user is assigned to at least 1 of them.
Has anybody done this? Any suggestions would be appreciated
I've located the 3 files related to the issue:
/app/controller/news_controller.rb
/app/models/news.rb
/app/views/news/_form.html.erb
Environment:
Redmine version 2.2.1.stable.11156
Ruby version 1.8.7 (x86_64-linux)
Rails version 3.2.11
Environment production
Database adapter MySQL
Redmine plugins:
no plugin installed
So far I've done only 1 modification in Redmine, which sends added news to all registered users.
File: /app/modelsmailer.rb
Overview:
EDIT: Following your advice I moved mailer function to the controller:
def create
#news = News.new(:project => #project, :author => User.current)
#news.safe_attributes = params[:news]
#news.save_attachments(params[:attachments])
if #news.save
#news_added(#news)
if params[:group]
mail :to => GroupsUser.find(params[:group][:ids]).joins(:users).select("users.mail").compact,
:subject => "[#{#news.project.name}] #{l(:label_news)}: #{#news.title}"
else
render :new
end
end
end
But I'm getting error: NameError (uninitialized constant NewsController::GroupsUser): pointing to line
mail :to => GroupsUser.find
news_controller.rb:
def new
#news = News.new
#groups = GroupsUser.all
end
news/_form.html.erb:
<%= label_tag :group_ids "Groups"
<%= collection_select :group, :ids, #groups, :id, :name, {}, multiple: true %>
Edit:
I'm going to have to take a few guesses on what your controllers look like, but I'll give you something close. Based on the mailer function you provided, I'm assuming that was called out of the create controller after the News was saved. I would call the mail function after that. Something like this:
def create
news = News.new(params[:news]
if news.save
news_added(news)
send_mail_to_groups(params[:group][:ids]) if params[:group]
redirect_to ...
else
render :new
end
end
The mailing part should be removed from news_added
def news_added(news)
redmine_headers 'Project' => news.project.identifier
#author = news.author
message_id news
#news = news
#news_url = url_for(:controller => 'news', :action => 'show', :id => news)
end
in favor of its own new routine:
send_mail_to_users_by_group_ids(group_ids)
# Woo: Sent to all users, despite their email settings
mail :to => GroupsUser.find(group_ids).joins(:users).select("users.mail").compact,
:subject => "[#{#news.project.name}] #{l(:label_news)}: #{#news.title}"
end
You might want to add a where clause to only include active users.
I think that's about right. I'm doing it off the top of my head so there's probably a typo or error or two in there. Hopefully it points you in the right direction though.
I'm having this problem, I tried a lot of differents aproachs but
everytime it falls in that error.
Enviroment:
Rails 3.0.5
Mongoid 2.0.1
class User
include Mongoid::Document
field :name
has_and_belongs_to_many :companies
end
class Company
include Mongoid::Document
field :name
has_and_belongs_to_many :users
end
In my UserController method Create a I do something like this:
#user = User.where(:email => params[:user][:email])
if #user.count > 0
#user.companies.push(#company)
#user.save
#company.users.push(#user)
#company.save
else
#user = User.create(:name => params[:user][:name],
:email => params[:user][:email],
:password => "123456")
#user.companies.push(#company)
#user.save
#company.users.push(#user)
#company.save
end
When the user dont exist works great.
But if the user is already in the DB, fall a error.
NoMethodError in UserController#create
undefined method `companies' for #<Array:0x10679f638>
But after all it pushes the object into the document.
I don't know if I'm missing something.
If someone know how to solve this ... will be great.
Thanks in advance.
Try this:
#user = User.where(:email => params[:user][:email]).first
On a side note, you may also want to push some of this code into one of your models, either the User or Company model, so that in your controller you would only have one call such as:
#company.add_user(#user)
The implementation details of adding a user would then be encapsulated in your model.
You may also want to consider embedding the two calls to ActiveRecord::Base#save into a single transaction to avoid ending up with inconsistent data in your database.
I am having a bit of an issue with getting tumblr working within a rails app.
This is the snippet of code which results in a 400 error (meaning that there was an incorrect parameter)
#postcontent = #post.content.gsub(/<\/?[^>]*>/, "")
post = Tumblr::Post.create(:email => 'valid#email', :password => 'mypassword', :type => 'video', :embed
=> #post.video_html, :caption => #postcontent)
I have checked the API docs and checked my code and code content being rendered, and it still does not want to work.
The funny thing is that it worked previously. It was working about a week ago. Has something changed with tumblr?
Update: I have also posted this on github in the issues section, and discovered that it's only with one of my posts that this method is not working, AND I have sent it over to the good people at tumblr. Has anyone else had this issue?
I HAVE WORKED THIS OUT ...
for anyone finding difficulty in this here is a solution.
Firstly, there was an error with the gem itself. Some code needs to be modified.
Check out this version of the gem:
http://github.com/mindreframer/tumblr
Secondly, as Tumblr allows html, I am calling sanitize within the controller to make my content nicely formatted and clean.
class PostsController < ApplicationController
include ActionView::Helpers::TextHelper
include ActionView::Helpers::SanitizeHelper
def tumblrsubmit
tumblruser = Tumblr::User.new('valid#email', 'validpass', false)
Tumblr.blog = 'blogname'
#post = Post.find(params[:id])
begin
unless #post.movie_id.nil? #checks if there is a movie ID
#tags = #post.tags.join(', ')
post = Tumblr::Post.create(tumblruser,
:type => 'video',
:embed => #post.video_html , #fetches the stored embed code
:caption => "Read Full Article & More at: <a href='http://www.mywebsite.com/posts/#{#post.slug}'>#{#post.title}</a> <p> </p>#{ActionController::Base.helpers.sanitize(#post.content)}",
:slug => #post.slug,
:tags => #tags )
else
post = Tumblr::Post.create(:tumblruser, :type => 'regular', :title => #post.title, :body => ActionController::Base.helpers.sanitize(#post.content), :slug => #post.slug)
end
#post.update_attributes(:tumbler_id => "#{post}") #updates the database with the new tumblr post id
flash[:notice] = "Successfully sent <strong>#{#post.title}</strong> to tumblr. with post id = #{post}"
rescue
flash[:error] = "You are unable to post <strong>#{#post.title}</strong> to tumblr at this time"
end
redirect_to :back
end
end
I know this seems like alot, but it does the job.
Hope this helps anyone else out there.
Cheers,
Matenia