jeudi 30 juillet 2015

Rails Users updating information in custom routes?

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?

Aucun commentaire:

Enregistrer un commentaire