I'm trying to save a form, and I am so lost on why it refuses to save. Does anybod have a clue what might be wrong?
Here's the form code:
<%= form_for #service, url: services_path do |f| %>
<% #profiles.each do |profile| %>
<%= f.text_field :service_id, value: "#{profile.service_id}" %>
<div class="media">
<a class="media-left" href="#">
<%= image_tag profile.avatar, height: '45', width: '45', class: 'img-circle' %>
</a>
<div class="media-body">
<h4 class="media-heading"><%= profile.service_username %></h4>
<%= profile.service %>
</div>
</div>
<% end %>
<%= f.submit %>
<% end %>
and
#service = current_user.services.new
the association between them are:
user has_many :services
service belongs_to :user
and the services controller create looks like this:
def create
#service = current_user.services.new(service_params)
if #service.save
flash[:notice] = "success"
redirect_to root_url
else
flash[:alert] = "Unable to add"
redirect_to :back
end
end
my logs say:
Started POST "/services" for 127.0.0.1 at 2015-01-17 18:09:44 -0800
Processing by ServicesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"lsW5aVuVUCQrHsaCo+uxbR11sF3mph3lTnM8O/Dtxn8=", "service"=> {"service_id"=>"2967861508"}, "commit"=>"Create Service"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = 30 ORDER BY "users"."id" ASC LIMIT 1
(0.2ms) BEGIN
(0.2ms) ROLLBACK
Redirected to http://localhost:3000/schedules
Completed 302 Found in 9ms (ActiveRecord: 1.1ms)
Oops, minor edit below (#service.errors instead of #validation.errors):
From your logs, you can see that you got into the controller create method and the save failed. This is usually a validation problem but I can't tell from what you posted. I would put #service.errors into the flash instead of just "unable to add". This should help you and future users see what's going on when the create fails.
Related
Im new at ruby and I try to add ajax for my controller, but I`m probably missing something
My controller
class StocksController < ApplicationController
def search
if params[:stock].present?
#stock = Stock.new_lookup(params[:stock])
if #stock
respond_to do |format|
format.js {render partial: 'users/result'}
end
else
flash[:alert] = "Please enter a valid symbol to search"
redirect_to my_portfolio_path
end
else
flash[:alert] = "Please enter a symbol to search"
redirect_to my_portfolio_path
end
end
end
My view. When I`m not writing 'turbo:false' nothing happens
<div class="search-area">
<h3>Search Stocks</h3>
<%= form_tag search_stock_path, data: {turbo: false}, method: :get do %>
<div class="form-group row">
<div class="col-sm-9 no-right-padding">
<%= text_field_tag :stock, params[:stock], placeholder: "Stock ticker symbol", autofocus: true, class: "form-control form-control-large"%>
</div>
<div class="col-sm-3 no-left-padding">
<%= button_tag type: :submit, class: "btn btn-success" do %>
<%= fa_icon 'search 1.5x' %>
<% end %>
</div>
</div>
<% end %>
</div>
My terminal:
Started GET "/search_stock?stock=MSFT&button=" for 127.0.0.1 at 2023-01-27 22:44:35 +0200
Processing by StocksController#search as HTML
Parameters: {"stock"=>"MSFT", "button"=>""}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
Completed 406 Not Acceptable in 1701ms (ActiveRecord: 1.2ms | Allocations: 8322)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/stocks_controller.rb:6:in `search'
Error image
I found articles with a similar error, but there was no answer
In the terminal I see that but dont know what to do
Processing by StocksController#search as HTML
I tried to do something similar to this in a form, but get this error:
Started POST "/opinions" for 127.0.0.1 at 2019-01-03 17:11:12 -0800
Processing by OpinionsController#create as JS
Parameters: {"utf8"=>"✓", "opinion"=>{"content"=>"This is an opinion"}, "type_of"=>"pro", "topicId"=>"{:value=>2}", "commit"=>"Create Opinion"}
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Topic Load (0.0ms) SELECT "topics".* FROM "topics" WHERE "topics"."id" = ? LIMIT ? [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 3ms (ActiveRecord: 0.0ms)
ActiveRecord::RecordNotFound (Couldn't find Topic with 'id'=):
app/controllers/opinions_controller.rb:6:in `create'
opinions_form.html.erb:
<%= form_for(opinion, :html=> {class:"form-horizontal", role:"form"}, remote: true) do |f| %>
<div class="form-group">
<div class="col-sm-12">
<%= f.text_area :content, rows:4, class: "form-control", placeholder: "Opinion" %>
</div>
</div>
<%= hidden_field_tag 'type_of', typeOf %>
<%= hidden_field_tag :topicId, :value => #topic.id %>
<% puts "ID: " + #topic.id.to_s %>
<div class="form-group">
<div class="col-sm-12">
<%= f.submit %>
</div>
</div>
<% end %>
Relevant code in controller:
def create
#opinion = Opinion.new(opinion_params)
#opinion.user = current_user
#opinion.topic = Topic.find(params[:opinion][:topicId])
if #opinion.save
flash[:success] = 'Opinion Added'
else
puts #opinion.errors.full_messages
flash[:danger] = 'Opinion not Added'
end
end
private
def opinion_params
params.require(:opinion).permit(:content, :type_of)
end
and finally, relevant code in the topic show page:
<td>
<%= render 'opinions/form', opinion: Opinion.new, typeOf: "pro", :topic => #topic %>
</td>
<td>
<%= render 'opinions/form', opinion: Opinion.new, typeOf: "con", :topic => #topic %>
</td>
As you can see in the request parameters:
Parameters: {"utf8"=>"✓", "opinion"=>{"content"=>"This is an opinion"}, "type_of"=>"pro", "topicId"=>"{:value=>2}", "commit"=>"Create Opinion"}
The topicId parameter is not nested under opinion, so you need to change your finder to:
#opinion.topic = Topic.find(params[:topicId][:value])
You can also remove the superfluous value key in your view:
<%= hidden_field_tag :topicId, #topic.id %>
Which would further simplify your finder:
#opinion.topic = Topic.find(params[:topicId])
As an aside. Note that idiomatic ruby calls for snake_case in all identifiers. This won't change how your code works, but it will help other Ruby developers read your code.
I followed the answer given here to create a simple dynamic form (not nested). The idea is to invite several people with their email. Then I have an "Add Team Member" button to add the fields to enter the coworker email.
I get the following error but I don't know why:
ActiveModel::ForbiddenAttributesError in InvitationsController#create
The parameters:
{"utf8"=>"✓",
"authenticity_token"=>"zLs8DWkzO+bPc2jGhFptgc+BAGAwzr1kcn/hkX/6vQbQ/cDCzuqoGCMGUTcYHs+up7nBzHFiEXVcKustyL1KIA==",
"invitation"=>[{"email"=>"test#test.fr", "_destroy"=>"false", "user_id"=>"1"}, {"email"=>"test2#test2.fr", "_destroy"=>"false", "user_id"=>"1"}],
"commit"=>"Save Team Members"}
My create action and invitation_params in the controller:
def create
puts params[:invitation].to_yaml
params[:invitation].each do |invitation_params|
Invitation.create(invitation_params)
end
redirect_to invitation_path
end
def invitation_params
params.require(:invitation).permit(:id, :email, :user_id, :_destroy, :token)
end
My form:
<%= form_for(invitation) do |f| %>
<% if invitation.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(invitation.errors.count, "error") %> prohibited this invitation from being saved:</h2>
<ul>
<% invitation.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div id="container_invitations"></div>
<%= link_to "Add a New Team Member", add_invitation_path, :method => :post, :remote => true %>
<div class="actions">
<%= f.submit "Save Team Members", class: "cta2" %>
</div>
<% end %>
add_invitation controller action (to add the fields dynamically):
def add_invitation
respond_to do |format|
format.js
end
end
add_invitation.js.erb:
$('#container_invitations').append("<%= escape_javascript(render :partial => 'invitation_fields_render') %>");
$('.remove_fields').on('click', function(e) {
$(this).parent().remove();
});
_invitation_fields_render.html.erb (the partial with the fields)
<div class="new_invitation_row">
<%= email_field_tag "invitation[][email]", nil, placeholder: "Team Member Email", :required => 'required' %>
<%= hidden_field_tag "invitation[][_destroy]", nil, value: false %>
<a class="remove-link remove_fields dynamic" href="#"><i class="fa fa-trash fa-lg" title="Remove"></i></a>
<%= hidden_field_tag "invitation[][user_id]", nil, value: current_user.id %>
</div>
My invitation model:
class Invitation < ActiveRecord::Base
has_secure_token
belongs_to :user
end
Thank you.
UPDATE
I added the new params.permit line proposed by IngoAlbers. I still get the error. Here is the full stacktrace of the error:
Started POST "/invitations" for 127.0.0.1 at 2017-12-01 07:49:02 +0000
Processing by InvitationsController#create as HTML Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"pV5wQj3QHXksNEtJ8nZSjWDc8VyHiewVCt4A1+ijH8G5GIyNmgmOh8BBcrhuMvCiCOQw8MYlQAQkiwprX+To5w==",
"invitation"=>[{"email"=>"test#test.fr", "_destroy"=>"false",
"user_id"=>"1"}], "commit"=>"Save Team Members"} User Load (0.4ms)
SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY
"users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]] CoreBot Load
(0.2ms) SELECT "core_bots".* FROM "core_bots" WHERE "core_bots"."id"
= ? LIMIT ? [["id", 1], ["LIMIT", 1]] Completed 500 Internal Server Error in 4ms (ActiveRecord: 0.6ms)
ActiveModel::ForbiddenAttributesError
(ActiveModel::ForbiddenAttributesError):
app/controllers/invitations_controller.rb:35:in block in create'
app/controllers/invitations_controller.rb:34:ineach'
app/controllers/invitations_controller.rb:34:in `create' Rendering
/Users/nicolasleroux/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb
within rescues/layout Rendering
/Users/nicolasleroux/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered
/Users/nicolasleroux/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
(5.3ms) Rendering
/Users/nicolasleroux/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb Rendered
/Users/nicolasleroux/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.5ms) Rendering
/Users/nicolasleroux/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered
/Users/nicolasleroux/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
(1.5ms) Rendered
/Users/nicolasleroux/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb
within rescues/layout (93.1ms)
The problem is that invitation is an array. So you actually need to permit the array in the invitation_params.
def invitation_params
params.permit(invitation: [:id, :email, :user_id, :_destroy, :token])
end
In addition you have a problem in the create action itself.
You don't actually use the permitted parameters, that was defined.
It should probably look like this:
def create
invitation_params[:invitation].each do |invitation|
Invitation.create(invitation)
end
redirect_to invitation_path
end
I have a Opportunity Model that has many Links. Links is a nested resource of Opportunity. On my views/opportunities/show.html.erb page, I display all the links that belong to that opportunity and I rendered a "new link" form as well. This form worked fine until recently and I am not sure why. When I fill out the "new link" form and click "add", the record does not save. Could someone please help me with this?
Here is my views/opportunities/show.html.erb page:
<%= render #opportunity %>
<form>
<fieldset>
<legend>Links</legend>
<div id="links">
<%= render #opportunity.links %>
</div>
<%= render :file => 'links/new' %>
</fieldset>
</form>
Here is my views/links/new page:
<%= form_for ([#opportunity, #opportunity.links.new]) do |f| %>
<div class="field">
<%= f.label "Description:" %> <br />
<%= f.text_field :description %>
</div>
<div class="field">
<%= f.label "URL:" %> <br />
<%= f.text_field :link_url %>
</div>
<div class="actions">
<%= f.submit 'Add' %>
</div>
<% end %>
Here is my create link controller:
def create
#opportunity = Opportunity.find(params[:opportunity_id])
#link = #opportunity.links.new(link_params)
if #link.save
redirect_to #opportunity, notice: 'link has been added'
else
redirect_to #opportunity, alert: 'Unable to add link'
end
end
Here is my Link model:
class Link < ActiveRecord::Base
belongs_to :opportunity
end
Here is my Opportunity model:
class Opportunity < ActiveRecord::Base
has_many :links
end
Here is the code from my console:
Started GET "/opportunities/7?utf8=%E2%9C%93&authenticity_token=ZLgPz98w2MjTChzzDXJ8EcqNmYNtBUG5DSYcp1CXReU%3D&link%5Bdescription%5D=testlink&link%5Blink_url%5D=testlink&commit=Add" for 127.0.0.1 at 2014-06-02 15:19:06 -0400
Processing by OpportunitiesController#show as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZLgPz98w2MjTChzzDXJ8EcqNmYNtBUG5DSYcp1CXReU=", "link"=>{"description"=>"testlink", "link_url"=>"testlink"}, "commit"=>"Add", "id"=>"7"}
Opportunity Load (0.2ms) SELECT "opportunities".* FROM "opportunities" WHERE "opportunities"."id" = ? LIMIT 1 [["id", 7]]
Rendered opportunities/_opportunity.html.erb (2.0ms)
Link Load (0.1ms) SELECT "links".* FROM "links" WHERE "links"."opportunity_id" = ? [["opportunity_id", 7]]
Rendered links/_link.html.erb (0.2ms)
Rendered links/new.html.erb (2.0ms)
Well, you need to debug it. I would start with adding the gem pry to your project.
Then you should temporarily change your code to something like:
def create
#opportunity = Opportunity.find(params[:opportunity_id])
#link = #opportunity.links.new(link_params)
if #link.save
redirect_to #opportunity, notice: 'link has been added'
else
binding.pry
redirect_to #opportunity, alert: 'Unable to add link'
end
end
In order to test it, you perform the add link action as usual. The code processing will stop at the line where binding.pry is being called. I assume here that the saving of therecord fails and we enter else part of the condition.
If I assume correctly, the link variable will be enriched with errors. In the console prompt of binding.pry just try to display them, if there are any (#link.errors)
I hope that helps.
I have a controller that is supposed to display a flash message. The flash message is not displaying.
My only problem is the flash messages not showing up. If anyone could please give an explanation for this that would be awesome. I am guessing that my error is noobish but i do not know enough to explain what is happening.
Edit: I added my Log for this section
Edit: When i click the manage button with invalid information nothing happens. When i refresh the page the flash message shows up. I really just need the current page refreshed but it is not working. If anyone has any ideas please share them.
Edit: I have tried changing things to
redirect_to #department, :notice => "invalid Password"
I am still not able to get the flash message to show up.
EDIT: From this site it says flash now will be displayed in the view that you are rendering. But my rendered view is a partial. Can anyone at least let me know if i am on the right track. A little direction or thought other than my own?
This is the create method for my relationship.
def create
#department = Department.find(params[:manager_relationship][:department_id])
if #department.authenticate(params[:manager_relationship][:password])
current_user.manage!(#department)
respond_to do |format|
format.html { redirect_to #department }
format.js
end
else
redirect_to department_path#department, :alert => "Invalid Password"
end
end
This same code is used successfully in my sessions controller.
SessionsController
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_back_or user
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
It is called from a partial
department/show.hmtl.erb
<% provide(:title, #department.department_name) %>
<div class="span8">
<%= render 'manage_form' if signed_in? %>
</div>
_manage_form.html.erb
<div id="manage_form">
<% if current_user.managing?(#department) %>
<%= render 'unmanage' %>
<% else %>
<%= render 'manage' %>
<% end %>
</div>
_manage.html.erb
<%= form_for(current_user.manager_relationships.build(department_id: #department.id), remote: true) do |f| %>
<div>
<%= f.label :password %>
<%= f.password_field :password %>
</div>
<div><%= f.hidden_field :department_id %></div>
<%= f.submit "Manage department", class: "btn btn-large btn-primary" %>
<% end %>
application.html.erb
<!DOCTYPE html>
<html>
<head>
.
.
.
...
<body>
<%= render 'layouts/header' %>
<div class="container">
<% flash.each do |key, value| %>
<div class="alert alert-<%= key %>"><%= value %></div>
<% end %>
<%= yield %>
<%= render 'layouts/footer' %>
</div>
Here is the log for an unmanage and manage http request
Started DELETE "/manager_relationships/22" for 127.0.0.1 at 2013-03-24 11:08:20 -0700
Processing by ManagerRelationshipsController#destroy as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Y3I7qY4LBfChjdYAUlJ1eDh23YkcJRwSRfa6s2wavoI=", "commit"=>"Unmanage", "id"=>"22"}
[1m[36mUser Load (0.0ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."remember_token" = '9J1RAJy16Tooz5wMmzQohw' LIMIT 1[0m
[1m[35mManagerRelationship Load (0.0ms)[0m SELECT "manager_relationships".* FROM "manager_relationships" WHERE "manager_relationships"."id" = ? LIMIT 1 [["id", "22"]]
[1m[36mDepartment Load (1.0ms)[0m [1mSELECT "department".* FROM "departments" WHERE "department"."id" = 1 LIMIT 1[0m
[1m[35mManagerRelationship Load (0.0ms)[0m SELECT "manager_relationships".* FROM "manager_relationships" WHERE "manager_relationships"."user_id" = 1 AND "manager_relationships"."department_id" = 1 LIMIT 1
[1m[36m (0.0ms)[0m [1mbegin transaction[0m
[1m[35mSQL (0.0ms)[0m DELETE FROM "manager_relationships" WHERE "manager_relationships"."id" = ? [["id", 22]]
[1m[36m (26.0ms)[0m [1mcommit transaction[0m
Rendered departments/_manage.html.erb (2.0ms)
Rendered manager_relationships/destroy.js.erb (5.0ms)
Completed 200 OK in 86ms (Views: 11.0ms | ActiveRecord: 27.0ms)
Started POST "/manager_relationships" for 127.0.0.1 at 2013-03-24 11:08:23 -0700
Processing by ManagerRelationshipsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Y3I7qY4LBfChjdYAUlJ1eDh23YkcJRwSRfa6s2wavoI=", "manager_relationship"=>{"password"=>"[FILTERED]", "department_id"=>"1"}, "commit"=>"Manage Bar"}
[1m[35mUser Load (0.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."remember_token" = '9J1RAJy16Tooz5wMmzQohw' LIMIT 1
[1m[36mDepartment Load (0.0ms)[0m [1mSELECT "departments".* FROM "departments" WHERE "departments"."id" = ? LIMIT 1[0m [["id", "1"]]
Redirected to http://localhost:3000/departments/1
Completed 406 Not Acceptable in 91ms (ActiveRecord: 0.0ms)
First, i can't see in your views where do you show the flash. You should do something like this in the view you want to display the message:
<% if flash[:success] %>
<p>
<%= flash[:success] %>
</p>
<% end %>
<% if flash[:error] %>
<p>
<%= flash[:error] %>
</p>
<% end %>
Second, when you do a redirection you should use flash[:success] = 'message' instead of flash.now[:success]. Use flash.now is you are not redirecting the user but just rendering a view.