【问题标题】:Rails Users updating information in custom routes?Rails 用户更新自定义路线中的信息?
【发布时间】:2015-10-22 13:16:33
【问题描述】:

不知道如何命名我的问题...

我的意图是用户将拥有一个项目列表(并且只有 current_user 可以编辑此列表)

class Item < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :items
end

我有一个用户控制器(注意:我也在使用设计 gem,但创建了一个单独的用户控制器)

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

现在我已经设置了路由

get 'users/:id/list', to: 'users#list', as: :list

这给了我这个:localhost:3000/users/1/list

理论上,这应该是显示视图...它将填充用户 ID 的项目列表:1。

我希望能够做到localhost:3000/list/edit 所以用户可以更新这个列表。

我在 views/users/list.html.erb 中的表单(我正在使用 cocoon gem 寻求嵌套表单的帮助)。

<%= 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 %>

我知道我的表单在我的 list.html.erb 中,它将填充所有项目,但我这样做只是出于测试目的。

如何更新表单以保存到项目数据库及其与当前用户的关联?

编辑:

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 routes


    【解决方案1】:

    在“显示”视图中使用表单并没有错。如果您只希望current_user 查看表单,请将您的表单包装在 if 语句中:

    <% if @user == current_user %>
      (form goes here...)
    <% end %>
    

    只要您有usersupdate 路由/操作,就应该提交该表单(免责声明:我从未使用过cocoon gem)。

    编辑:您的表单应该没问题。将此路由添加到您的 routes.rb 文件中:

    patch 'users/:id', to: 'users#update'
    

    【讨论】:

    • 好吧,我正试图弄清楚我的更新操作和路由对于表单以及何时(或是否)需要编辑,该操作会是什么样子
    • 将路线添加到我的答案
    • 现在我得到The action 'update' could not be found for UsersController。我是否只是从我搭建的另一个更新操作中复制?
    • 哦,是的,update 操作只是一种定期更新方法。所以是的,你可以复制它。只需确保替换所有变量以使其有意义即可。
    • 如此接近!我收到unknown attribute 'items_attributes' for Item. 有什么想法吗?这应该来自我的参数对吗?但我相信我所有的属性都是正确的
    【解决方案2】:

    对于当前用户身份验证,您应该使用cancan gem https://github.com/ryanb/cancan

    对于与用户nested_form 相关的嵌套字段,gem 是最佳选择 https://github.com/ryanb/nested_form

    【讨论】:

    • 这并没有真正帮助我。 @RyanK 的回答帮助了我!
    • 当然。我在我的项目中使用了这两个宝石,它们让我的生活变得轻松。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2022-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多