Reputation: 8597
Not sure how to title my question...
My intent is that users will have a list of items (and only the current_user can edit this list)
class Item < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :items
end
I have a Users controller (note: I'm also using devise gem, but created a separate Users Controller)
class UsersController < ApplicationController
load_and_authorize_resource
def show
@user = User.find(params[:id])
end
def list
@user.items.build
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(
items_attributes: [:user_id, :item, :name, :_destroy]).merge(user_id: current_user.id)
end
end
Right now I have set up routing
get 'users/:id/list', to: 'users#list', as: :list
Which gives me this: localhost:3000/users/1/list
Theoretically, this should be the show view... where it'll populate the list of items for user id: 1.
I want to be able to do localhost:3000/list/edit
So the user can update this list.
My form in views/users/list.html.erb (I'm using cocoon gem for help with nested forms).
<%= simple_form_for @user do |f| %>
<%= f.simple_fields_for :items do |i| %>
<%= f.text_field :item %>
<%= f.text_field :name %>
<% end%>
<%= link_to_add_association 'add item', f, :items %>
<%= f.button :submit %>
<% end %>
I know my form is in my list.html.erb where it'll populate all the items, but I'm just doing this for testing purposes.
How do I update the form to save into items database and its associated with the current user?
EDIT:
def update
@user = current_user.items.find_by_user_id(current_user.id)
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'Congrats on your successful update!' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
Upvotes: 1
Views: 36
Reputation: 540
For current user authentication you should use cancan
gem
https://github.com/ryanb/cancan
For nested fields related to user nested_form
gem is the best option
https://github.com/ryanb/nested_form
Upvotes: 0
Reputation: 4053
There is nothing wrong with having a form in a "show" view. If you only want the current_user
to view the form, then wrap your form in an if statement:
<% if @user == current_user %>
(form goes here...)
<% end %>
As long as you have an update
route/action for users
, that form should submit (disclaimer: I've never used the cocoon
gem).
Edit: Your form should be fine as is. Add this route to your routes.rb
file:
patch 'users/:id', to: 'users#update'
Upvotes: 1