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
Related
I'm getting a "Unpermitted Parameters: :event_id, :attendee_id" even though I'm whitelisting the params
Started POST "/planned_events" for 127.0.0.1 at 2014-08-22 22:08:39 +0900
Processing by PlannedEventsController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"WhVcJWjo08KWqxFViUPbSZVMYzu2UgGW9E+WRExP9Wc=", "planned_event"=>
{":event_id"=>"3", ":attendee_id"=>"1"}, "commit"=>"Attend"}
Unpermitted parameters: :event_id, :attendee_id
(0.0ms) begin transaction
SQL (0.4ms) INSERT INTO "planned_events" ("created_at", "updated_at") VALUES (?, ?)
[["created_at", Fri, 22 Aug 2014 13:08:39 UTC +00:00], ["updated_at", Fri, 22 Aug 2014
13:08:39 UTC +00:00]]
(1.8ms) commit transaction
Unpermitted parameters: :event_id, :attendee_id
Completed 500 Internal Server Error in 9ms
ActionController::UrlGenerationError (No route matches {:action=>"show",
:controller=>"events", :id=>nil} missing required keys: [:id]):
app/controllers/planned_events_controller.rb:6:in `create'
Here is controllers/planned_events_controller.rb
class PlannedEventsController < ApplicationController
def create
#planned_event = PlannedEvent.new(planned_event_params)
if #planned_event.save
redirect_to event_path(planned_event_params[:event_id])
end
end
def destroy
#planned_event = PlannedEvent.find(params[:id]).destroy
redirect_to event_path(planned_event_params[:event_id] => :id)
end
private
def planned_event_params
params.require(:planned_event).permit(:event_id, :attendee_id)
end
end
Why?
The broswer is highlighting the "redirect_to..." line with the error.
ActionController::UrlGenerationError in PlannedEventsController#create
No route matches {:action=>"show", :controller=>"events", :id=>nil} missing required keys:
[:id]
I assume the :id is nil because it wont accept the id i'm passing it (from the whitelisted params), and can't find an alternative.
Your parameters have wrong names:
{":event_id"=>"3", ":attendee_id"=>"1"}
Change them in your form, incoming parameters should be
{"event_id"=>"3", "attendee_id"=>"1"}
Also, you can change whole redirect_to to shorter version:
redirect_to #planned_event.event
its a routes error.instead of moving to create its moving to show action of controller.
remember:-
your create link should be post
your show action should be get(with id passed)
i think your view needs to be looked upon where you are clicking.check the link_to or submit button or your form_for
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.
So I'm working on this part of a rails app with nested forms. I am having trouble with getting validation to work. So the parent form is a model to store Questions and the child form is a model to store Answers.
There are 3 different types of questions: number (text field), yes/no (radio buttons), agree/disagree (radio buttons).
I have a simple validation in the answers model: validates :value, presence: true
So for example I create a question of type number, it generates a text field and if I submit it as empty the validation works and the errors are rendered on the page. However, if I pick one of the the other 2 options, which are both radio buttons, I can submit the form without making a selection and the validation doesn't work. I noticed in the console that only the question is inserted into the database, but the answer is not (with the radio button form); normally I would assume that at least there would be nil values passed, but the INSERT query doesn't even show up.
I cheated a little by having a hidden field in the radio button forms, and creating a change handler that sets the value of the radio button to the hidden field whenever the radio button selected is changed. However, I would really like to dig deeper and figure out the real issue, because it's always good to have a back-up in case javascript is disabled.
Answer Model
class Answer < ActiveRecord::Base
attr_accessible :value, :user_id, :meter_id, :question_id
belongs_to :user
belongs_to :question
validates :value, presence: true, :numericality => true
before_save :associate_with_meter_id
before_save :associate_with_user_id
def associate_with_meter_id
self.meter_id = question.user.meter_id
end
def associate_with_user_id
self.user_id = question.user.id
end
end
Question Model
class Question < ActiveRecord::Base
attr_accessible :description, :taxonomy, :user_id, :answers_attributes
belongs_to :user
has_many :answers
accepts_nested_attributes_for :answers
validates :description, presence: { :on => :create }
validates :taxonomy, presence: { :on => :create }
def relevance_score
rand
end
end
Log
Started POST "/questions" for 127.0.0.1 at 2012-06-12 09:21:25 -0400
Processing by QuestionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"knwvfB6q6Q7qoTprc/3R4Et3r13xWzpAB1Iq8FsRndQ=", "question"=>{"description"=>"How are you?", "taxonomy"=>"yesno"}, "submit_button"=>"Ask"}
User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 585460615 LIMIT 1
SQL (0.1ms) BEGIN
SQL (4.3ms) INSERT INTO `questions` (`avganswer`, `coeff`, `created_at`, `description`, `pval`, `quality`, `rank`, `responses`, `rsquare`, `skips`, `taxonomy`, `updated_at`, `user_id`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["avganswer", nil], ["coeff", nil], ["created_at", Tue, 12 Jun 2012 13:21:25 UTC +00:00], ["description", "How are you?"], ["pval", 0.0], ["quality", 0.0], ["rank", nil], ["responses", nil], ["rsquare", 0.0], ["skips", nil], ["taxonomy", "yesno"], ["updated_at", Tue, 12 Jun 2012 13:21:25 UTC +00:00], ["user_id", 585460615]]
(0.3ms) COMMIT
SQL (0.0ms) BEGIN
(0.0ms) COMMIT
Redirected to http://localhost:3000/questions
Completed 302 Found in 14ms (ActiveRecord: 0.0ms)
Started GET "/questions" for 127.0.0.1 at 2012-06-12 09:21:25 -0400
Processing by QuestionsController#index as HTML
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 585460615 LIMIT 1
Question Load (1.3ms) SELECT `questions`.* FROM `questions` WHERE `questions`.`user_id` = 585460615
Rendered shared/_error_messages.html.erb (0.0ms)
Rendered questions/_form.html.erb (23.9ms)
(0.5ms) SELECT COUNT(*) FROM `questions`
Rendered questions/index.html.erb within layouts/application (48.8ms)
Question Load (1.6ms) SELECT `questions`.* FROM `questions`
(0.4ms) SELECT COUNT(*) FROM `questions` WHERE `questions`.`user_id` = 585460615
Rendered /Users/gregorygrillone/.rvm/gems/ruby-1.9.3-p194/bundler/gems/gauges-58ad28a906b2/app/views/gauges/_gauge.html.erb (0.1ms)
CACHE (0.0ms) SELECT `questions`.* FROM `questions`
CACHE (0.0ms) SELECT COUNT(*) FROM `questions` WHERE `questions`.`user_id` = 585460615
Completed 200 OK in 72ms (Views: 62.2ms | ActiveRecord: 4.2ms)
Started GET "/assets/application.css" for 127.0.0.1 at 2012-06-12 09:21:25 -0400
Served asset /application.css - 304 Not Modified (0ms)
[2012-06-12 09:21:25] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
Started GET "/assets/application.js" for 127.0.0.1 at 2012-06-12 09:21:25 -0400
Served asset /application.js - 304 Not Modified (0ms)
[2012-06-12 09:21:25] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
Question controller
class QuestionsController < ApplicationController
respond_to :html, :json
def index
#question = current_user.questions.new
#questions = current_user.questions.all
end
def create
#question = current_user.questions.new(params[:question])
if !params[:update_button]
if #question.valid?
if params[:next_button] || !#question.save
#questions = current_user.questions.all
render 'index'
elsif !params[:next_button] && params[:submit_button] && #question.save
flash[:success] = "Your question and answer have been saved."
respond_with #question, :location => questions_path
end
else
#questions = current_user.questions.all
render 'index'
end
else
#questions = current_user.questions.all
render 'index'
end
end
def next
#question = current_user.unanswered.first
#answer = Answer.new(:question => #question, :user => current_user)
respond_to do |format|
format.js
end
end
end
I think your view code is not creating the form structure properly.
You should be able to confirm your controller code is correct, by writing a functional/controller test that posts the params in the format you expect. (much better/faster feedback than trying to post half your app up to StackOverflow!)
You will be able to create a decent test in less than an hour, and that knowledge will make everything else you do that much better and faster. Trust me, it will be worth the effort of learning how to properly test your code.
Once you prove that you have the controller working properly, you'll most likely find that your view code is not creating the form inputs of the nested answer properly. You can see from the log file that it didn't even attempt to post them.
You might want to separate the create and update actions, the code that checks for different buttons is a bit confusing and makes it hard to understand the 'contract' between the page and the controller. (eg. if next but not update but submit...) That's not causing your problem now, but just something you might want to clean up before it bites you later.
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.