I'm trying to create user-generated posts. I know that the posts are being created in the
db, but are not displaying. Terminal puts:
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
SQL (18.4ms) INSERT INTO "events" ("content", "created_at", "updated_at",
"user_id") VALUES (?, ?, ?, ?) [["content", "Test post."], ["created_at",
Sat, 15 Oct 2011 06:36:49 UTC +00:00], ["updated_at",
Sat, 15 Oct 2011 06:36:49 UTC +00:00], ["user_id", 1]]
Redirected to http://localhost:3000/events
Started GET "/events" for 127.0.0.1 at Sat Oct 15 00:36:49 -0600 2011
Processing by EventsController#show as HTML
Completed 404 Not Found in 1ms
ActiveRecord::RecordNotFound (Couldn't find Event without an ID):
app/controllers/events_controller.rb:22:in `show'
Saying the same thing, but my app gives me the same error:
Couldn't find Event without an ID
app/controllers/events_controller.rb:22:in `show'
Is this a problem with my Events_Controller method "show":
def show
#title = "Your Events"
#event = Event.find(params[:id])
end
Or a routine issue? I'm trying to display an index of all events created.
Thanks in advance for any help.
In EventsController on line 13 you have:
redirect_to events_path
I believe this corresponds to the sixth line in your log above ("Redirected to http://localhost:3000/events").
When you use redirect_to, however, it initiates a new GET request, and as you did not specify any parameters params is consequently empty. That's why params[:id] is nil and Event.find(params[:id]) throws the error you're seeing.
Instead of using redirect_to, are you sure you shouldn't be using render :action => :show or render :action => :index? Unlike redirect_to, render does not initiate a new request, it merely renders the specified view, but within the current context (where, in your case, #event is already defined.
For more information on render vs. redirect_to read the Rails Guide on Layouts and Rendering, section 2 in particular.
Related
This is my first app in Rails 4, but I'm not sure whether Rails 4 is the problem.
I have nested resources as follows:
resources :made_games do
resources :made_game_instances
end
When I try to save a new made_game_instance this is what's happening in the log:
Started POST "/made_games/11/made_game_instances" for 127.0.0.1 at 2013-09-10 12:03:55 -0700
Processing by MadeGameInstancesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"jEN2syjftjRtf3DBnijtp7gNVUEFrI+HYTUs+HFgo5M=", "made_game_instance"=>{"new_word1"=>"bluesky"}, "commit"=>"Create Made game instance", "made_game_id"=>"11"}
MadeGame Load (122.7ms) SELECT "made_games".* FROM "made_games" WHERE "made_games"."id" = $1 LIMIT 1 [["id", "11"]]
(14.0ms) BEGIN
SQL (215.9ms) INSERT INTO "made_game_instances" ("created_at", "made_game_id", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["created_at", Tue, 10 Sep 2013 19:03:55 UTC +00:00], ["made_game_id", 11], ["updated_at", Tue, 10 Sep 2013 19:03:55 UTC +00:00]]
(5.7ms) COMMIT
Redirected to http://localhost:3000/made_games/11/made_game_instances/5
Completed 302 Found in 458ms (ActiveRecord: 358.3ms)
You can see that the params hash contains the hash where the new_game_instance attribute :new_word1 is assigned the value "bluesky." What I cannot figure out is why this assignment does not appear in the SQL that is subsequently generated when the new 'made_game_instances' object is created.
Additional information
Since this is Rails 4, in order to whitelist all the parameters (at least at this stage in development), I have used permit! in the params private method at the bottom of the controllers for both made_games and made_game_instances.
The made_games controller:
class MadeGamesController < ApplicationController
def new
#made_game = MadeGame.new
end
def create
#made_game = MadeGame.new(made_game_params)
if #made_game.save
flash[:notice] = "Here you go!"
redirect_to #made_game
else
flash[:notice] = "Something about that didn't work, unfortunately."
render :action => new
end
end
def show
#made_game = MadeGame.find(params[:id])
end
private
def made_game_params
params.require(:made_game).permit!
end
end
Here is a link to the github repo: https://github.com/keb97/madlibs/tree/users_making
The form used to create a new made_game_instance is:
<%= simple_form_for [#made_game, #made_game_instance] do |f| %>
<p>
<%= f.input :new_word1, label: #made_game.word1.to_s %>
</p>
<%= f.button :submit %>
<% end %>
I should also note that there is one form for made_game, and a separate form for made_game_instance, rather than a nested form, so I do not believe this is an issue of accepts_nested_attributes_for or fields_for.
In your made_games_instance_controller.rb
this line...
#made_game_instance = #made_game.made_game_instances.build(params[:made_game_instance_params])
should actually be...
#made_game_instance = #made_game.made_game_instances.build(made_game_instance_params)
There is no params hash entry with a symbol key :made_game_instance_params
I'm fairly new to Rails, so this will likely end up being something obvious; however I've just spent the better part of a day pulling my hair out over this issue.
I have a rails app which I've been working on for awhile, however I only started implementing mailers today. I followed the Rails ActionMailer tutorial here: http://guides.rubyonrails.org/v3.0.3/action_mailer_basics.html and the mailer works fine in a new example app. However, when I repeated those steps verbatim in my existing rails app (running in Development environment) I receive the below error. It creates the entry in the DB, correctly sends both the plain text & HTML emails and THEN generates the error. All I'm trying to do here is send a welcome email upon the creation of a new account, but I'm getting the same error when I try to send any email from any controller.
The specific error I'm seeing after it sends the welcome email is:
Completed 500 Internal Server Error in 280ms
NoMethodError (undefined method `error' for true:TrueClass):
app/controllers/musers_controller.rb:52:in `block in create'
app/controllers/musers_controller.rb:50:in `create'
Note that to not mess up my existing User table, I created a temporary scaffold & mailer called Muser which I plan on deleting once I'm confident this will work correctly on my user table.
Code
Error in log:
Started POST "/musers" for 127.0.0.1 at 2013-07-10 20:32:34 -0400
Processing by MusersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"OuoEmsjkAVBHZwqPO5b/O4eKw6iZBaLP6vUT6f9WCOI=", "muser"=>{"name"=>"New User", "email"=>"User#email.com"}, "commit"=>"Create"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "musers" ("created_at", "email", "name", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Thu, 11 Jul 2013 00:32:34 UTC +00:00], ["email", "User#email.com"], ["name", "New User"], ["updated_at", Thu, 11 Jul 2013 00:32:34 UTC +00:00]]
(1.7ms) commit transaction
Rendered muser_mailer/registration_confirmation.html.erb (0.1ms)
Rendered muser_mailer/registration_confirmation.text.erb (0.0ms)
Completed 500 Internal Server Error in 280ms
NoMethodError (undefined method `error' for true:TrueClass):
app/controllers/musers_controller.rb:52:in `block in create'
app/controllers/musers_controller.rb:50:in `create'
Rendered /usr/local/rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_dispatch/middleware/templates/rescues/_trace.erb (2.6ms)
Rendered /usr/local/rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (2.5ms)
Rendered /usr/local/rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (15.3ms)
--I should note that lines 50 & 52 of the musers_controller (where this error is being generated) correspond to the 'respond_to do' & 'MuserMailer.... .deliver' lines in the controller code below.--
The controller action:
# POST /musers
# POST /musers.json
def create
#muser = Muser.new(params[:muser])
respond_to do |format|
if #muser.save
MuserMailer.registration_confirmation(#muser).deliver
format.html { redirect_to #muser, notice: 'Muser was successfully created.' }
format.json { render json: #muser, status: :created, location: #muser }
else
format.html { render action: "new" }
format.json { render json: #muser.errors, status: :unprocessable_entity }
end
end
end
Mailer:
class MuserMailer < ActionMailer::Base
default from: "EmailAddress#Inter.net"
def registration_confirmation(muser)
#muser = muser
mail(:to => muser.email, :subject => "Registered")
end
end
I don't think that the issue is with my smtp, mail setup, or variables since it does actually add to the DB & send the emails correctly. If I comment out the line in the controller which calls the mail action the error disappears, so I don't think the problem is with my muser routes. This undefined method 'error' for true:TrueClass is driving me nuts. I did recently install Devise on my Users table, so I don't know if that could be causing the issue?
For lack of a better term, it feels like the issue is with how Rails wants to route after sending the emails; as if I need to put a Return or specify a route at the end of my mailer action telling the server to head back to the controller action. In other words, I'm lost!
Update
Below are the two mailer view files I'm using.
registration_confirmation.html.erb
<h3><%= #muser.name %>! You sweet sweet fool!</h3>
<p>Thank you for registering!</p>
registration_confirmation.text.erb
Thank you for registering!
Update 2
Here's my model for Muser:
class Muser < ActiveRecord::Base
attr_accessible :email, :name
end
I solved this issue - there was the errant line config.action_mailer.logger = true in my config/environments/development.rb file that was causing the issues. Once removed everything worked perfectly.
The task model has just one field : title.
I've made a form to add a new task with one single field : title
But in the create method, we can see that title is filled by "test"
but in the query, we can see "nil" ... any ideas ?
thanks
Started POST "/tasks" for 127.0.0.1 at 2013-01-03 13:16:44 -0500
Processing by TasksController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"iWaK1QX6VCyeUCueLrRNErJEtdm/ZNxg4d3LU0vKjnY=", "task"=>{"title"
=>"test"}, "commit"=>"Add a new task "}
(0.1ms) begin transaction
SQL (0.9ms) INSERT INTO "tasks" ("created_at", "title", "updated_at") VALUES (?, ?, ?) [["created_at", Thu, 03 Jan 2013 18:16:44 UTC +00:00], ["title", nil], ["updated_at", Thu, 03 Jan 2013 18:16:44 UTC +00:00]]
(0.8ms) commit transaction
Redirected to http://0.0.0.0:3000/tasks
Completed 302 Found in 8ms (ActiveRecord: 1.8ms)
here is the create method
def create
#task = Task.new(params[:post])
if #task.save
redirect_to tasks_path, :notice => "Task successfully saved"
else
render "new"
end
end
The problem is that you are fetching post instead of task
#task = Task.new(params[:task])
Make sure your attribute is accessible or you won't be able to mass-assign changes to it:
class Task < ActiveRecord::Base
attr_accessible :title
end
You should have unit tests that properly exercise your models to be sure that they can be updated as you do in the controller. Those will quickly uncover any attributes which have not been correctly flagged.
Rails 2.3 and prior were not strict about this, you could mass-assign anything, but Rails 3 will not assign these attributes unless they are specifically allowed.
Make sure
attr_accessible :title
is in your Task model (task.rb)
UPDATE:
change params[:post] to params[:task]:
#task = Task.new(params[:task])
In your tasks_controller.rb , you must have create method which will handle POST request and accept parameters which are passed though request .
def create
task = Task.new(params[:task])
task.save
end
I have this in the Model:
after_create do |comment|
CommentMailer.comment_email(self).deliver
end
This in CommentMailer:
class CommentMailer < ActionMailer::Base
helper ActionView::Helpers::UrlHelper
include CommentHelper
helper :comment
def comment_email(user, comment, commentable)
mail(to: user.email,
subject: "You have left a comment",
from: "comments#lumeo.com",
bcc: "brian#lumeo.com")
end
end
And this in CommentHelper:
module CommentHelper
def find_commentable
#comment = Comment.find(params[:comment])
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
I'm getting this error:
Started POST "/requests/6/comments" for 127.0.0.1 at 2012-11-30 17:28:55 -0800
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"R62NH5/EE34FPapEqy7mfpa0wKz18GtSdhH8MGYq2Ec=", "comment"=>{"content"=>"post", "show"=>"true"}, "commit"=>"Create Comment", "request_id"=>"6"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY users.created_at DESC LIMIT 1
Request Load (0.3ms) SELECT "requests".* FROM "requests" WHERE "requests"."id" = $1 LIMIT 1 [["id", "6"]]
CACHE (0.0ms) SELECT "requests".* FROM "requests" WHERE "requests"."id" = $1 LIMIT 1 [["id", "6"]]
(0.1ms) BEGIN
SQL (0.4ms) INSERT INTO "comments" ("commentable_id", "commentable_type", "content", "created_at", "show", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["commentable_id", 6], ["commentable_type", "Request"], ["content", "post"], ["created_at", Sat, 01 Dec 2012 01:28:55 UTC +00:00], ["show", true], ["updated_at", Sat, 01 Dec 2012 01:28:55 UTC +00:00], ["user_id", 2]]
(0.2ms) ROLLBACK
Completed 500 Internal Server Error in 136ms
ArgumentError (wrong number of arguments (1 for 3)):
app/mailers/comment_mailer.rb:5:in `comment_email'
app/models/comment.rb:27:in `block in <class:Comment>'
app/controllers/comments_controller.rb:22:in `create'
Looks like simple typos.
Line 7, as noted in the exception:
commentable = #comment.commentable
So, the issues:
You're calling #comment.commentabe, but #comment is nil
Hence the error: undefined method 'commentable' for nil:NilClass
#comment is nil in your mailer method because you're passing it in as comment NOT #comment, yet you're trying to reference it as #comment.
Also, why are you passing in commentable as a parameter, but on line 7 you're setting commentable again - this is redundant? Just use the already available commentable variable that you're passing in as a param. In fact, you seem to be doing this with several variables, yet I can't tell (because you don't show the mailer template) whether or not you're actually using them.
It could be that you could use something simpler like:
So, this should (probably) work:
def comment_email(user, comment, commentable)
mail(to: user.email,
subject: "You have left a comment",
from: "comments#lumeo.com",
bcc: "brian#lumeo.com")
end
If you post your mail template (so I can see what the body of the email looks like) I can help you get the variables into the template.
I've got this basic model, where a provision object, a nested resource of a bill, can have three types of effective date types. Suffice to say, if the client picks the third option "On a specific date", I got a bit of JQuery popping up a second field with a datepicker so he can select that datetime value.
However, for the past few hours I've been pulling my hair trying to figure out why the server receives the parameters correctly, but enters the value for the datetime as nil. I've tried every single trick in the book to resolve this (even tried dropping the column and recreating it). I'm sure I'm missing something quite obvious. Please help :-(
Here's my code, let's start
first with the Server response (the parameter in question is called date_of_effect):
Started POST "/bills/1/provisions" for 127.0.0.1 at 2011-08-18 22:27:42 -0400
Processing by ProvisionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"v6B+sgSsOsPXOGl2TulguIpfXaRmvTBzUJ7Qge/aNhM=", "provision"=>{"article"=>"2", "text"=>"testing this", "in_effect"=>"3", "date_of_effect"=>"08/25/2011"}, "commit"=>"Create Provision", "bill_id"=>"1"}
SQL (0.6ms) INSERT INTO "provisions" ("article", "bill_id", "created_at", "date_of_effect", "in_effect", "order_id", "text", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?) [["article", 2], ["bill_id", 1], ["created_at", Fri, 19 Aug 2011 02:27:42 UTC +00:00], ["date_of_effect", nil], ["in_effect", 3], ["order_id", nil], ["text", "testing this"], ["updated_at", Fri, 19 Aug 2011 02:27:42 UTC +00:00]]
Bill Load (0.1ms) SELECT "bills".* FROM "bills" WHERE "bills"."id" = 1 LIMIT 1
Redirected to http://localhost:3000/bills/1
Completed 302 Found in 230ms
The relevant fields of my view look like this:
<div class="datelabel">Select a date</div>
<div class="datelabel"><%= f.text_field(:date_of_effect) %></div>
...
<% content_for :bottom do %>
<script>
$(function() {
$(".datelabel").hide();
$('#provision_date_of_effect').datepicker();
$('#provision_in_effect').change(function() {
($(this).val() == '3') ? $('.datelabel').show('puff') : $('.datelabel').hide();
});
});
</script>
<% end %>
And finally my create method in the controller (notice the comment lines are me trying out different methods to get the datetime to stick, to no avail unfortunately):
def create
#provision = Provision.new(params[:provision])
#provision.bill_id = params[:bill_id]
#provision.save
# #provision.date_of_effect = params[:provision][:date_of_effect]
# #provision.save(:validate => false)
flash[:notice] = "Section added"
redirect_to #provision.bill
end
Any help would be greatly appreciated, thanks :)
You can do this:
#provision.date_of_effect = Date.strptime(params[:provision][:date_of_effect], '%m/%d/%Y') if !params[:provision][:date_of_effect].blank?
Or you can change format for datepicker. Date can't parse this format "08/25/2011"