Link to remote issue is not working correctly - ruby-on-rails

Here is the live demo
I'm trying to show listbox using remote actions just searching params, but is not working.
Clients_controller.rb
def new
#client.new
end
def search_city
#cities = City.where('id= ?',params[:city_id])
respond_to do |format|
format.js
end
end
search_city.js.erb
$("#test").html("<%= escape_javascript(render(:partial => "city_results"))%>");
Models
Client.rb
belongs_to :city
City.rb
belongs_to :state
has_many :clients
State.rb
has_many :cities
Routes.rb
resources :clients do
match 'search_city',:via =>[:get], :on => :collection
end
_form.erb
<%= link_to "Get list cities", {:action => "search_city"}, :remote => true, :class => "button-link" %>
<div id = "test">Here this text will be replaced</div>
_city_results.erb
<%= select_tag "example",options_for_select(#cities.collect { |p| [p.name,p.id] }) %>
Here complete log:
Started GET "/clients/new" for 127.0.0.1 at 2016-04-14 17:31:03 -0500
Processing by ClientsController#new as HTML
Completed 200 OK in 133ms (Views: 107.4ms | ActiveRecord: 1.0ms)
Rendered client_management/clients/new.html.erb within layouts/application (21.6ms)
Started GET "/clients/search_city?city_id=1" for 127.0.0.1 at 2016-04-14 16:43:55 -0500
Processing by ClientManagement::ClientsController#search_city as JS
Parameters: {"city_id"=>"1"}
Province Load (0.2ms) SELECT `states`.* FROM `states` WHERE `states`.`city_id` = 1
Rendered clients/partials/_city_results.erb (1.9ms)
Rendered clients/search_city.js.erb (2.9ms)
Completed 200 OK in 7ms (Views: 4.7ms | ActiveRecord: 0.4ms)
INFO
SELECT `states`.* FROM `states` WHERE `states`.`city_id` = 1
RESULT: 1 (exist value)
PROBLEM:
Is not showing the select tag with options.
When I check if params are sended everything is ok but in the view is not replaced.
Need to install a gem?
Is just working with simple text without but need rails code.
I tried this:
$('#province').html("<%= escape_javascript( render :partial => 'clients/partials/city_results' ) %>");
$('#province').show();

def search city
....
respond_to do |format|
format.js
end
end

Related

Rails 7 not executing code within controller method on POST

I have a really basic Rails 7 application at the moment. Using all the defaults.
For some reason, Rails is not entering/running the code within a controller I've defined.
Here is the related route.
scope module: 'admin', path: 'admin', as: 'admin' do
root 'home#index'
resources :users do
post :invite, on: :collection
end
end
Here is the related Controller method:
def invite
puts "INVITE" * 100
invite_params = params.require(:admin_invite).permit(:name, :email)
#invite = Admin::Invite.new(invite_params)
respond_to do |f|
if #invite.send_invite
f.html { redirect_to admin_users_url, notice: "Invite sent" }
else
f.html { redirect_to admin_users_url, status: :unprocessible_entity, error: "There was an error sending the invite" }
end
end
end
Here is the form that POSTs to that route.
= form_with model: #new_invite, url: invite_admin_users_url, html: {"data-turbo" => false} do |f|
= f.label :name
= f.text_field :name
= f.label :email
= f.email_field :email
= f.submit "Invite"
I thought maybe it had something to do with TURBO that comes with Rails 7, so I disabled it on this form, but it didn't resolve the issue.
When I click submit on that form, I get the following error: No template found.
Looking at the output in the terminal, it seems to be POSTing properly to the controller, but it's not running any of the code with the method. Even that puts statement I have at the beginning of the #invite method doesn't execute.
19:26:14 web.1 | Started POST "/admin/invite_user" for ::1 at 2022-09-07 19:26:14 -0400
19:26:14 web.1 | Processing by Admin::UsersController#invite as HTML
19:26:14 web.1 | Parameters: {"authenticity_token"=>"[FILTERED]", "admin_invite"=>{"name"=>"Test", "email"=>"test#test.com"}, "commit"=>"Invite"}
19:26:14 web.1 | User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
19:26:14 web.1 | No template found for Admin::UsersController#invite, rendering head :no_content
Any ideas?

Error making duplicate get requests

I have a problem where my controller action is creating duplicate records. I have a search form that checks the database for a record, or if its not in the database, scrapes a website to create the record. This same action (not restful i know) is also creating a record of the search itself with a value of "success" or "failure" depending on if the record could be found. However, it is consistently duplicating the record of the search. Here is the form_tag:
<%= form_tag new_search_path, remote: true, method: :get, id: 'etf-lookup-form' do %>
...
<%= text_field_tag :etf, params[:etf], placeholder: "ETF ticker symbol EX: SPY", autofocus: true, class: 'form-control search-box input-lg', style: "text-transform: uppercase" %>
and the controller:
class SearchesController < ApplicationController
def new
if params[:etf]
#etf = Etf.find_by_ticker(params[:etf].upcase)
#etf ||= Scraper.new_from_lookup(params[:etf].upcase)
end
if #etf.present?
Search.create(ticker: params[:etf].upcase, user_id: current_user.id, status: "success" )
render :js => "window.location = '#{etf_path(#etf)}'"
else
Search.create(ticker: params[:etf].upcase, user_id: current_user.id, status: "failure" )
render :js => "window.location = '#{search_path}'"
end
end
The terminal output always shows the get request being made twice before rendering the new page. How can I solve this problem? And/or what is a better way to organize these controller actions? I also have an EtfsController which contains a show action. Here are a couple fragments of from the terminal:
Started GET "/search/new?utf8=%E2%9C%93&etf=spy&button=" for ::1 at 2017-05-01 20:05:49 -0400
Processing by SearchesController#new as JS
Parameters: {"utf8"=>"✓", "etf"=>"spy", "button"=>""}
.......
Completed 200 OK in 10ms (Views: 0.1ms | ActiveRecord: 2.0ms)
Started GET "/search/new?utf8=%E2%9C%93&etf=spy&button=" for ::1 at 2017-05-01 20:05:49 -0400
Processing by SearchesController#new as JS
...
Completed 200 OK in 9ms (Views: 0.1ms | ActiveRecord: 2.7ms)
Started GET "/etfs/1" for ::1 at 2017-05-01 20:05:49 -0400
Processing by EtfsController#show as HTML
...
Completed 200 OK in 126ms (Views: 117.9ms | ActiveRecord: 1.2ms)
Probably you can refactor your code to look like this and the problem should be gone:
before_action :set_etf, only: [:new]
after_action :create_search, only: [:new]
def new
render js: window_location
end
private
def create_search
Search.create(ticker: etf_params, user_id: current_user.id, status: "success" )
end
def etf_params
#etf_params ||= params[:etf].to_s.upcase
end
def set_etf
#etf = (Etf.find_by_ticker(etf_params) || Scraper.new_from_lookup(etf_params) if etf_params.present?
end
def window_location
return "window.location = '#{etf_path(#etf)}'" if #etf.present?
"window.location = '#{search_path}'"
end
This should do the trick, let me know how it goes!

Couldn't find Project with 'id'= when trying to create a Task from Project profile

I have a projects model and a task model, however a task can have many projects and vice versa...so i created a relationship model between the two. Now from the project profile, i want to be able to create a task and automatically have it create the task and the relationship between the new task and the project it was created from.
However when i try to accomplish this i am getting the following error:
ActiveRecord::RecordNotFound in TasksController#create
Couldn't find Project with 'id'=
A user is on the Project show page and clicks a link to 'submit new task'. I realize i'm not passing the project ID somehow but I can't seem to figure out how to do this because I'm using a TaskRelationship model to associate the task and the project (I'm not nesting the task in the project in my routes).
views/projects/show.html.erb:
<%= link_to "+ Submit New Task", new_task_path, :class => "btn btn-info col-md-12" %>
From the new tasks view, I need to create both the task and the relationship between task and project.
views/tasks/new.html.erb:
<div class="container sign-in-register">
<div class="authform">
<%= form_for #task, :html => {:multipart => true} do |f| %>
<h3>Submit new task to this project...</h3><br/>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :Title %>
<%= f.text_field :title, class: 'form-control' %>
<%= f.label :Description %>
<%= f.text_area :description, class: 'form-control' %>
<br clear="all">
<%= f.submit "Add this Task", class: "btn btn btn-info" %>
<% end %>
</div>
</div>
TaskRelationship Model (links tasks to projects):
class TaskRelationship < ActiveRecord::Base
belongs_to :taskproject, class_name: "Project"
belongs_to :projecttask, class_name: "Task"
validates :taskproject_id, presence: true
validates :projecttask_id, presence: true
end
Project Model:
class Project < ActiveRecord::Base
belongs_to :owner, :foreign_key=>'user_id', :class_name=>'User'
has_many :tasks
has_many :taskrelationships, foreign_key: "taskproject_id", dependent: :destroy
has_many :projecttasks, through: :taskrelationships, source: :projecttask
validates :title, presence: true
validates :background, presence: true
def related?(some_task)
taskrelationships.find_by_projecttask_id(some_task.id)
end
def relate!(some_task)
self.taskrelationships.create!(projecttask_id: some_task.id)
end
end
Task Model:
class Task < ActiveRecord::Base
belongs_to :owner, :foreign_key=>'user_id', :class_name=>'User'
has_many :projects
has_many :reverse_taskrelationships, foreign_key: "projecttask_id",
class_name: "TaskRelationship",
dependent: :destroy
has_many :taskprojects, through: :reverse_taskrelationships, source: :taskproject
validates :title, presence: true
validates :description, presence: true, length: { maximum: 140 }
end
Tasks Controller:
class TasksController < ApplicationController
def new
#task = Task.new
end
def create
#project = Project.find(params[:taskproject_id])
#task = current_user.own_tasks.build(task_params)
if #task.save
flash[:success] = "Your task has been created."
redirect_to #task
#project.relate!(#task) unless #project.related?(#task) # establish task relationship w/ project only if doesn't exist
else
render 'task'
end
end
private
def task_params
params.require(:task).permit(:title, :description, :user_id, task_relationship_attributes: [:taskproject_id, :projecttask_id])
end
end
Task_Relationships_Controller:
class TaskRelationshipsController < ApplicationController
before_filter :authenticate_user!
def create
end
def destroy
end
# I assume (maybe incorrectly) that i don't need create/destroy actions but do need strong params
private
def task_relationship_params
params.require(:taskrelationship).permit(:taskproject_id, :projecttask_id)
end
end
How can i get this correct ID passed so that the new task is created and the new taskRelationship between task and project? thx,
UPDATE:
I've added the log for more detail
Terminal Log when trying to post:
Started GET "/tasks/new" for ::1 at 2016-04-15 19:55:54 -0500
Started GET "/tasks/new" for ::1 at 2016-04-15 19:55:54 -0500
Processing by TasksController#new as HTML
Processing by TasksController#new as HTML
Rendered shared/_error_messages.html.erb (0.1ms)
Rendered shared/_error_messages.html.erb (0.1ms)
Rendered tasks/new.html.erb within layouts/application (24.5ms)
Rendered tasks/new.html.erb within layouts/application (24.5ms)
Rendered layouts/_shim.html.erb (0.0ms)
Rendered layouts/_shim.html.erb (0.0ms)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 4]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 4]]
Rendered layouts/_navigation_links.html.erb (1.6ms)
Rendered layouts/_navigation_links.html.erb (1.6ms)
Rendered layouts/_header.html.erb (2.9ms)
Rendered layouts/_header.html.erb (2.9ms)
Rendered layouts/_footer.html.erb (0.0ms)
Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 192ms (Views: 185.6ms | ActiveRecord: 1.0ms)
Completed 200 OK in 192ms (Views: 185.6ms | ActiveRecord: 1.0ms)
Started POST "/tasks" for ::1 at 2016-04-15 19:55:59 -0500
Started POST "/tasks" for ::1 at 2016-04-15 19:55:59 -0500
Processing by TasksController#create as HTML
Processing by TasksController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"DGGG+zWPMbB7OwZz8oCVLB5O6sMfTe/Orj6KfeP6mrveOH0ImAP4aow0gufqefOdwsp8v4GDEt8ppJiL4CvQVg==", "task"=>{"title"=>"test", "description"=>"test"}, "commit"=>"Add this Evidence"}
Parameters: {"utf8"=>"✓", "authenticity_token"=>"DGGG+zWPMbB7OwZz8oCVLB5O6sMfTe/Orj6KfeP6mrveOH0ImAP4aow0gufqefOdwsp8v4GDEt8ppJiL4CvQVg==", "task"=>{"title"=>"test", "description"=>"test"}, "commit"=>"Add this Evidence"}
Project Load (0.3ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT 1 [["id", nil]]
Project Load (0.3ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT 1 [["id", nil]]
Completed 404 Not Found in 2ms (ActiveRecord: 0.3ms)
Completed 404 Not Found in 2ms (ActiveRecord: 0.3ms)
ActiveRecord::RecordNotFound (Couldn't find Project with 'id'=):
app/controllers/tasks_controller.rb:8:in `create'
ActiveRecord::RecordNotFound (Couldn't find Project with 'id'=):
app/controllers/tasks_controller.rb:8:in `create'
1) You'll need to pass the project ID to TasksController#new somehow.
One approach is to pass it as part of the request URL, something like:
<host>/tasks/new?project_id=<project ID>
This will make it available in the params variable of the request.
2) In your TasksController#new action, pass project_id from params to the view. The easiest way is using an instance variable:
#project_id = params[:project_id]
There is a philosophy of only passing one object to a view and here we're passing 2: #task and #project_id. I wouldn't worry about it but you might want to read up on form objects: https://robots.thoughtbot.com/activemodel-form-objects
3) Add a hidden field on your form with the project ID. Because #project_id isn't part of the #task model, we'll use an input tag helper instead of a form based helper:
<%= hidden_field_tag 'project_id', #project_id %>
API doc: http://apidock.com/rails/ActionView/Helpers/FormTagHelper/hidden_field_tag
Now the value of #project_id will be passed to the #create action as params[:project_id] when the user clicks on the submit button.
4) Change the params in TasksController#create action. project_id will be nested in with the task parameters:
#project = Project.find(params[:project_id])
5) You'll need to create your TaskRelationship relationship. There are a couple of ways to do this. I usually use build:
#task.taskprojects.build(project: #project)
so your #create action would look something like:
#project = Project.find(params[:project_id])
#task = current_user.own_tasks.build(task_params)
#task.taskprojects.build(project: #project)
if #task.save
...
In your controller statement Project.find(params[:taskproject_id]), it looks like params[:taskproject_id] is nil. Looking at the code in your form view the params passed to the controller should be params[:id]. It's also not clear where task_params is defined
If you still are getting the error, check the params in the log output from when you submit your form and post them here.

Rails 4 API with Strong Parameters?

I'm building a simple API with Rails 4, but with my "create" method, it all goes horribly wrong.
Here is the relevant part of my routes file:
namespace :api, defaults: { format: 'json' } do
# /api/... Api::
scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
resources :users
end
end
Here is the api/v1/users_controller.rb:
class Api::V1::UsersController < ApplicationController
protect_from_forgery except: :create
respond_to :json
def index
respond_to do |format|
format.html {render text: "Your data was sucessfully loaded. Thanks"}
format.json { render text: User.last.to_json }
end
end
def show
respond_with User.find(params[:id])
end
def create
respond_with User.create(user_params)
end
def update
respond_with User.update(params[:id], params[:users])
end
def destroy
respond_with User.destroy(params[:id])
end
private
def user_params
params.require(:user).permit(:name, :age, :location, :genre_ids => [], :instrument_ids => [])
end
end
Whenever I try to add an API with JSON, I get "{"errors":{"name":["can't be blank"]}}"
It works to create a user with my regular controller, but I have a feeling my API controller is getting messed up because of the Strong Parameters.
Any suggestions for how to do this correctly in Rails 4?
Also, I have a few Has-Many-Through relationships through my user model. The API's user controller should be able to see that off the bat, right?
Thanks
EDIT:
I'm now getting this error:
EDIT:
{
"name": "Sally",
"age": "23",
"location": "Blue York",
"genre_ids": [1, 2, 3]
}
EDIT AGAIN
Even with adding the User parameter in my JSON call, it still gives me the same error of the :user param missing. Am I using strong parameters incorrectly? In my "regular" users_controller, I can create a user easily with a form that I have set up, but with this API controller, I can't seem to create one with JSON. Any other suggestions?
EDIT YET AGAIN
Here Is The Log From Start to Error
rails s
=> Booting WEBrick
=> Rails 4.0.1 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2013-12-19 14:03:01] INFO WEBrick 1.3.1
[2013-12-19 14:03:01] INFO ruby 1.9.3 (2013-02-22) [x86_64-darwin10.8.0]
[2013-12-19 14:03:01] INFO WEBrick::HTTPServer#start: pid=53778 port=3000
Started GET "/api/users" for 127.0.0.1 at 2013-12-19 14:03:02 -0500
ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by Api::V1::UsersController#index as JSON
User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
Rendered text template (0.0ms)
Completed 200 OK in 142ms (Views: 27.8ms | ActiveRecord: 0.6ms)
[2013-12-19 14:03:03] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
[2013-12-19 14:03:03] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
Started POST "/api/users" for 127.0.0.1 at 2013-12-19 14:03:37 -0500
Processing by Api::V1::UsersController#create as JSON
Completed 400 Bad Request in 1ms
ActionController::ParameterMissing (param not found: user):
app/controllers/api/v1/users_controller.rb:40:in `user_params'
app/controllers/api/v1/users_controller.rb:20:in `create'
Rendered /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack- 4.0.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.7ms)
Rendered /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.8ms)
Rendered /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack- 4.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (31.6ms)
EDIT #6
Here is my "real" users_controller that lives in my app and not my API. The form creates a user from this controller and NOT the API controller.
class UsersController < ApplicationController
def index
#users = User.all
#genres = Genre.all
#instruments = Instrument.all
render json: #users
end
def new
#user = User.new
end
def show
#user = User.find(params[:id])
end
def create
#user = User.new(user_params)
if #user.save
render json: #user, status: :created, location: #user
else
render json: #user.errors, status: :unprocessable_entity
end
end
private
def user_params
params.require(:user).permit(:name, :age, :location, :genre_ids => [], :instrument_ids => [])
end
end
ALSO - The User Form
<div class="row">
<div class="span6 offset3">
<%= form_for(#user) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :age %>
<%= f.text_field :age %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :location %>
<%= f.text_field :location %>
<br>
<% Genre.all.each do |genre| %>
<%= check_box_tag "user[genre_ids][]", genre.id %>
<%= genre.name %><br>
<% end %>
<br>
<% Instrument.all.each do |instrument| %>
<%= check_box_tag "user[instrument_ids][]", instrument.id %>
<%= instrument.name %><br>
<% end %>
<%= f.submit "Create My Account!" %>
<% end %>
</div>
</div>
<%= users_path %>
Here is my user.rb File
class User < ActiveRecord::Base
validates :name, presence: true, length: { maximum: 50 }
has_many :generalizations
has_many :genres, through: :generalizations
has_many :instrumentations
has_many :instruments, through: :instrumentations
end
Here is what I have in my routes file:
namespace :api do
namespace :v1 do
resources :users
end
end
My POST Request
POST /api/v1/users HTTP/1.1
Host: localhost:3000
Cache-Control: no-cache
{ "user": { "name": "Sally", "age": "23", "location": "Blue York", "genre_ids": [1, 2, 3] } }
UPDATE
I changed my strong-params to be this:
def user_params
params.require(:user).permit(:name, :age, :location, :genre_ids => [], :instrument_ids => []) if params[:user]
end
So the "if" statement at the end makes the error go away, but whenever I post to my API, it gives me back "null". So this could be the same problem as before, but shown in a different way. But, at the same time, it could be progress!
Here Is The Log For The Previous Update
Started POST "/api/v1/users" for 127.0.0.1 at 2013-12-21 11:38:03 -0500
Processing by API::V1::UsersController#create as */*
(0.1ms) begin transaction
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
(0.1ms) rollback transaction
User Load (0.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
Rendered text template (0.0ms)
Completed 200 OK in 20ms (Views: 0.3ms | ActiveRecord: 0.6ms)
FINAL UPDATE
I was missing a few things, but the main thing that did it was that I was missing "Content-Type - application/json" as my Header.
I feel so accomplished! Thanks for all your help, everyone!
According to your code parameters in the JSON you are posting should be inside params[:user]. So the JSON should look like:
{
"user": {
"name": "Sally",
"age": "23",
"location": "Blue York",
"genre_ids": [1, 2, 3]
}
}
Rails 4 is a great choice for building APIs. I would go with the rails-api gem. It will perform way better than a full blown Rails stack.
I have built plenty of API's in Rails using the Rails API gem. Usually in combination with RABL (which you can use to create nice templates to render your JSON). I am not a big fan of integrating an API directly into your production Rails app (serving websites and JSON) as you will create a big mess over time when starting to add more versions to your API. There are some very good Railscasts (www.railscasts.com): Search for API.
When accessing your API you would use a global filter in your application_controller.rb file. You could do something like this:
before_filter :authenticate_user, :except => 'users#index'
private
def authenticate_user
#current_user = User.find_by_api_key(params[:token])
unless #current_user
render :status=>403, :json=>{:message=>"Invalid token"}
end
end
def current_user
#current_user
end
end
In this case you would send the token in your request (that's quick and dirty, rather use the header instead) as a request parameter. You need to add the API key or whatever you want to use to your user model. Just create a migration adding api_key or however you want to call it to the user model or create a new table with keys, secrets etc. and a user_id field for your belongs_to (and a User has_many api_keys, or has_one). This way you can allow your users at any time to change their keys etc. (re-generate) without messing with usernames/password or even allow them to have multiple API keys with some tags (testing, production, etc). For your user signup you could add to your model:
before_create :generate_api_key
and then create a simple method like:
def generate_api_key
begin
self.api_key = SecureRandom.hex
end while self.class.exists?(api_key: api_key)
end
Hope it helps!

update form redirecting to root_url on submit - Rails 3

Updated w/ dev log. See below
I'm using vanity urls in my routing and I"m assuming it has something to do with it...
In short my issue is I'm unable to have the user update their information. I can get the edit form to show up but on submit the update method doesn't run and I neither get a "fail" or "success".
The relevant routes look like this:
resources :users do
resources :friends
end
match '/:username/edit' => 'users#edit', :as => "edit_user"
match '/:username' => 'users#show', :as => "user"
My form looks like this now, but I've tried a couple different things.
<%= form_for #user, :url => user_path(#user.username) do |form| %>
<%= render 'shared/error_messages', :object => form.object %>
<div class="form">
<p> <%= form.label :description, "Message to friends" %> <br />
<%= form.text_area :description %> </p>
<%= form.submit "Update" %>
</div>
<% end %>
The edit and update controllers look like this:
def edit
#user = User.find_by_username(params[:username])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
redirect_to user_url(current_user.username), :flash => { :success => "wham" }
else
redirect_to user_url(current_user.username), :error => { :error => "shiz" }
end
end
Currently, when the update form is submitting, you get directed to the users url but nothing happens. I'd appreciate any help. Thanks!
Update ----
I have changed my routes as described below using to_param. This works just fine but the problem still persists where my update form just redirects to the root_url. Under rake routes I get the correct path for update and the edit form is displaying correctly. Here is what I get form rake routes:
PUT /users/:id(.:format) {:controller=>"users", :action=>"update"}
And this is the dev log from submitting my form
Started POST "/1" for 127.0.0.1 at Wed Jan 05 16:09:54 -0500 2011
Processing by UsersController#show as HTML
Parameters: {"commit"=>"Update User", "authenticity_token"=>"OM1lIzizuFCYlxC3XmtmG/btqAsyjekHtqsiwlUDn3M=", "utf8"=>"✓", "username"=>"1", "user"=>{"description"=>"Update the message please"}}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE ("users"."username" = '1') LIMIT 1
Redirected to http://0.0.0.0:3000/
ApplicationController::current_user
ApplicationController::current_user_session
User Load (0.2ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 1) LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 1) LIMIT 1
ApplicationController::current_user_session
Completed 302 Found in 44ms
Started GET "/" for 127.0.0.1 at Wed Jan 05 16:09:54 -0500 2011
Processing by PagesController#home as HTML
ApplicationController::current_user
ApplicationController::current_user_session
User Load (0.2ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 1) LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 1) LIMIT 1
ApplicationController::current_user_session
ApplicationController::current_user
ApplicationController::current_user
ApplicationController::current_user
ApplicationController::current_user
Rendered pages/home.html.erb within layouts/application (22.2ms)
Completed 200 OK in 61ms (Views: 32.4ms | ActiveRecord: 0.2ms)
Why does that redirect happen??
Rather than defining custom routes for this, just define the to_param method on the User class:
def to_param
username.parameterize
end
Then for your routes, the params[:id] value will be the username's paramertized version. For instance, mine would be ryan-bigg.
Even though your log doesn't indicate this is the case, I'd also check if the attr_accessible has :description added to it in User model. It's happened to me before - the form seems to work but information doesn't get stored.

Resources