【问题标题】:Update Association with JSON Object更新与 JSON 对象的关联
【发布时间】:2016-03-07 09:44:07
【问题描述】:

我想使用 JSON API 更新 company.nameuser 属于company。我们可以做些什么来确保用户不应该更新他们不属于的公司?注意user 可能没有公司

我查看了validates_associated,但我不确定它会如何实现。注意,我们从前端传递了一个公司对象。

class User < ActiveRecord::Base
  belongs_to :company
end

class Company < ActiveRecord::Base
  has_many :users
end

class CompanyController < ApplicationController
  def update
    if @current_user.company.update_attributes(params[:company])
      render updated and return
    else
      render not_found and return
    end
  end
  def company_params
    params.require(:company).permit(:name)
  end
end

describe "#update" do
  it " company name" do
    @company.name = "new_name"
    put :update, :token_id => "fake_token_id", :id => @company.id, :company => {:name => @company.name}
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-4 activerecord


    【解决方案1】:

    在您的 update 操作中执行此操作:

    def update
      company = Company.find(params[:id])
      if !@current_user.company.nil? and company == @current_user.company
        if @current_user.company.update_attributes(params[:company])
          render updated and return
        else
          render fail_to_update and return
        end
      else
        render not_found and return
      end
    end
    

    【讨论】:

    • 这应该引发DoubleRenderError 异常。
    • @Зелёный 你能解释一下这是怎么发生的吗?
    • @Yang,我忘记在示例代码中添加“并返回”以防止双重渲染。我的错,“渲染 fail_to_update 并返回”
    • 您能否添加“并在您的渲染后返回,然后我可以接受答案”
    • 我在 update_attributes 命令上也得到一个“ActiveModel::ForbiddenAttributesError”。请看修改后的代码
    【解决方案2】:

    由于您在 @current_user.company 上调用 update_attributes,因此该公司将始终属于 @current_user,并且它将是唯一被更新的公司。

    现在,如果您出于任何原因将公司更新参数提交到您的#update 操作并且用户没有您可以添加的公司:

    def update
      if @current_user.company && @current_user.company.update_attributes(params[:company])
        render updated
      else
        render not_found
      end
    end
    

    【讨论】:

    • 如果您查看测试代码,该 API 请求中有一个 param[:id]。我认为检查它是否与current_user 的公司匹配将使逻辑更可靠。
    • 由于该操作旨在更新 @current_user 的公司 params[:id] 已过时
    • 我们必须记住,您的解决方案会更新 current_users 公司,而不考虑 param[:id]。所以传递另一个公司参数[:id],仍然会更新 current_user.company 属性。在 REST API 中,我认为请求应该失败。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多