I have has_many association and want get Users Websites and from console user.websites gives me list of all websites, but when I try in controller:
def index
#websites = User.find(params[:user_id]).websites
end
Gives me error:EDIT
Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (3.0ms)
Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (99.0ms)
←[1m←[36mUser Load (2.0ms)←[0m ←[1mSELECT `users`.* FROM `users` WHERE `users`.`id` =67 LIMIT 1←[0m
Completed 500 Internal Server Error in 2ms
ActiveRecord::RecordNotFound (Couldn't find User without an ID):
app/controllers/websites_controller.rb:10:in `index'
but I am logged in and do have user with id =67:
User.find(67)
=> #<User id: 67, first_name: "admin", ...
In my view:
<% #websites.each do |website| %>
<%= website.name %>
<%= website.url %>
<p> <%= website.category %>
<%= website.language %>
<%end%>
EDIT.Tried to inspect params[:user_id] in index view, and this didn't show me anyhing:
<%= params[:user_id]%>
Why I'm getting errors ?
Where are you getting the params[:user_id] from?
Have you tried:
def index
#websites = User.find(params[:id]).websites
end
You need to explain how you are finding the user.
You said that you are logged in, so do you have a current_user?
def index
#websites = current_user.websites
end
or do it in parts:
def index
#user = #find the user
#websites = #user.websites
end
Related
I'm using the carrierwave gem to upload images
I have this form in my users view which provides an upload button for a file (image)
<%= form_for(#user, html: { multipart: true }) do |f| %>
Update your profile pic:
<span class="avatar">
<%= f.file_field :avatar %>
</span>
<%= f.submit "Update", class: "btn btn-primary" %>
<% end %>
Here's my users controller
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:avatar)
end
end
When I click the submit button on the form from the browser, I get this http request come through.
Started PATCH "/users/1" for 127.0.0.1 at 2018-07-05 13:15:39 +0100
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"VXaEvnTD7nl+2d/0n1+iB/zwRX+Mf3nbMt0/Qr7m/nYpTmyXCxih981pIbGKGT9qdSfB7zyB6l
CKGdA9uiLouw==", "user"=>{"avatar"=>#<ActionDispatch::Http::UploadedFile:0x00007fbf2a794af0 #tempfile=#<Tempfile:/var/folders
/42/plkmf9zn755b0lvwc2_5k30c0000gn/T/RackMultipart20180705-37847-7s1tba.png>, #original_filename="Screen Shot 2018-07-03 at 1
0.23.17.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"user[avatar]\"; filename=\"Screen S
hot 2018-07-03 at 10.23.17.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"Update", "id"=>"1"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], [
"LIMIT", 1]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
No template found for UsersController#update, rendering head :no_content
Completed 204 No Content in 161ms (ActiveRecord: 0.6ms)
But nothing is updated in the database (i.e. the avatar attribute for the current user still has a value of nil). I also can't see that the image has been saved anywhere.
It's your controller update method which is incomplete, for example :
def update
user = User.find(params[:id]) # Set user
if user.update(user_params) # Save to database
# Success, redirect to show/index/whatever
else
# Fail, render form again
end
end
And i recommend you to read this: http://guides.rubyonrails.org/action_controller_overview.html
Context - I am creating a simple authentication, following the line by line instruction from https://www.youtube.com/watch?v=Hw6WtWJwRtU.
Steps completed so far -
Created a User Table. The table has columns user_name and password_digest
In User model mentioned 'has_secure_password'
Uncommented bcrypt in gemfile and executed bundle install
Created a controller sessions, created a new method 'Create' that has form to get username and password.
Error - On entering the user name and passowrd in the login form, I am getting error No method defined.
Steps taken so far to correct -
1. Checked the table schema, the table has column password_digest and column type is varchar
2. gem list - mentions that bcrypt is installed. I closed rails server and restarted again too.
Please find the snippet -
User Model -
class User < ActiveRecord::
attr_accessible :user_name, :password
has_secure_password
belongs_to :UserType
def find_by_name(name)
user = User.find_by(user_name: name)
end
end
Sessions Controller -
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_name(params[:user_name])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to root_url, notice: "Logged In"
else
flash.now.alert = "Email or password is invalid"
render new
end
end
end
Session View -
<h1>Log In</h1>
<%= form_tag sessions_path do %>
<div class="field">
<%= label_tag :user_name %>
<%= text_field_tag :user_name, params[:user_name] %>
</div>
<div class="field">
<%= label_tag :password %>
<%= password_field_tag :password %>
</div>
<div class="action"><%= submit_tag "Log In" %></div>
<%end%>
users table -
CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "user_name" varchar, "password_digest" varchar, "UserType_id" integer, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);
CREATE INDEX "index_users_on_UserType_id" ON "users" ("UserType_id");
Routes -
Rails.application.routes.draw do
resources :sessions
resources :feedback_details
resources :users
resources :meetings
resources :user_types
root 'sessions#new'
Error Log -
Started POST "/sessions" for 127.0.0.1 at 2017-01-29 14:24:43 +0530
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"BvROFNObaYS/8Fq8wjTLwh6DiWo5rcLNnfvpdhlxgD2vhEmx2ErXWJRA8ku6bHYBRZ8W2imI2N/+SMMlnuWz+w==", "user_name"=>"tushar", "password"=>"[FILTERED]", "commit"=>"Log In"}
Completed 500 Internal Server Error in 24ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method `has_secure_password' for ActiveRecord:Module):
app/models/user.rb:2:in `<top (required)>'
app/controllers/sessions_controller.rb:6:in `create'
Rendered /usr/lib/ruby/vendor_ruby/action_dispatch/middleware/templates/rescues/_source.erb (8.6ms)
Rendered /usr/lib/ruby/vendor_ruby/action_dispatch/middleware/templates/rescues/_trace.html.erb (4.0ms)
Rendered /usr/lib/ruby/vendor_ruby/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.8ms)
Rendered /usr/lib/ruby/vendor_ruby/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (31.6ms)
Rendered /var/lib/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.7ms)
Rendered /var/lib/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.6ms)
Rendered /var/lib/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.6ms)
Rendered /var/lib/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.6ms)
Rendered /var/lib/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (25.3ms)
Rendered /var/lib/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.6ms)
Rendered /var/lib/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.8ms)
Rendered /var/lib/gems/2.3.0/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (51.1ms)
Please let me know, if I need to provide more information.
You're missing a teeny bit of code here.
class User < ActiveRecord::Base
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.
I have a company model designed with the devise , and when the company is logged in the company can create the event so that the company has many events and events belong to company the events controller is given as
class EventsController < ApplicationController
before_action :company_signed_in?
def index
#events = Event.all
end
def new
#event = current_company.events.build
end
def create
#event = current_company.events.build(event_params)
if #event.save
flash[:success] = "Profile saved"
redirect_to company_events_path(current_company)
else
flash[:error] = "Error"
render :new
end
end
def show
#event = current_company.events.where(id: params[:id]).first
end
private
def event_params
params.require(:event).permit(:name, :company_id, :category_id, :event_date, :event_info, :place, :event_avatar)
end
end
and the company model has
has_many :events
and the event model has
belongs_to :company
the new view of the event has
<%= form_for [current_company, #event] do |f| %>
<%= f.text_field :name %>
<% end %>
and the show view has
<%= #event.name %>
my routes are
resources :companies do
resource :company_profile, :events
end
now what i want to do is the current company can create an event and when the event is created it should be redirected to the show page of the event just produced
i need to create an event so that i can get the url like companies/3/events/3 this type of url
issue is when i am going to the show action i am getting undefined method 'name' Please help ! and in the log i have
Started GET "/companies/3/events" for 127.0.0.1 at 2015-07-30 16:41:54 +0530
Processing by EventsController#show as HTML
Parameters: {"company_id"=>"3"}
Company Load (0.3ms) SELECT `companies`.* FROM `companies` WHERE `companies`.`id` = 3 ORDER BY `companies`.`id` ASC LIMIT 1
CompanyProfile Load (0.3ms) SELECT `company_profiles`.* FROM `company_profiles` WHERE `company_profiles`.`company_id` = 3 LIMIT 1
Event Load (0.3ms) SELECT `events`.* FROM `events` WHERE `events`.`company_id` = 3 AND `events`.`id` IS NULL ORDER BY `events`.`id` ASC LIMIT 1
Rendered events/show.html.erb within layouts/application (12.5ms)
Completed 500 Internal Server Error in 32ms (ActiveRecord: 0.8ms)
ActionView::Template::Error (undefined method `name' for nil:NilClass):
1:
2: <label>Name : </label>
3: <%= #event.name %>
4: <%= #event.event_date %></br></br>
5: <label>Age : </label>
6: <%= #event.place %></br></br>
app/views/events/show.html.erb:3:in `_app_views_events_show_html_erb__541678279__634038278'
you are not passing id of event to the show action. only company_id is passed as shown in parameters
Parameters: {"company_id"=>"3"}
so when it queries in the event with id NULL it didnt find any event and hence null.name is crashing
Either pass id of event to the show action. or for testing you should do this
def show
#event = current_company.events.first
end
You should try the below method and see if it works:
def show
#event = Event.find(params[:id])
end
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.