我有以下测试代码:

...
let(:person) { create(:person) }
...

it 'test the create route' do
  json_data = '{"data":{"attributes":{"email":"[email protected]","position":""},
           "relationships": {"person":{"data":{"id":' + person.id.to_s + ',"type":"people"}}},
          "type":"users"}}'

  post 'create', body: json_data, format: :json

  json = JSON.parse(response.body)

  expect(response).to have_http_status(:success)
end

此代码测试控制器类方法:
public def create
  action(User::Create)
    .otherwise('user_create_error', 401)
    .then_render(User::Representer::Out::Default)
end

动作方法:
public def action(op = nil, effective_params = params)
  return if op.nil?

  # Call the operation
  result = op.(effective_params,
    'current_user' => current_user,
    'document' => request.raw_post)

  # Build and return the OperationResult object
  Webapp::OperationResult.new(result, method(:render))
end

op是执行命令的操作(开拓者操作):
class User::Create < Webapp::Operation
  contract User::Contract::Default

  step Model(User, :create)
  step Policy::Pundit(User::Policy, :create?)
  step Contract::Build()
  step Contract::Validate(representer: User::Representer::In::Default)
  step Contract::Persist()
end

现在我得到了错误,那个人是零。为什么?我在创建一个用户之前保存这个人,数据也会一起发送。所有需要的属性都包含在representative中,在用户模型中还有一个指向person(belongs_to)的链接person模型还包含指向用户(has_many)的链接工厂的用户和人员也都在那里,并填写了数据。事实上,这必须没有任何问题,但它没有。
由于我无法解释的原因,储蓄(坚持)是不可能的以下是用户模型:
class User < ApplicationRecord

  # Associations
  belongs_to :person

  delegate :firstname, to: :person
  delegate :surname, to: :person

  ....
end

还有什么要交给代表或为代表准备的吗?

最佳答案

我认为,你必须在操作中添加一个set_person方法:

 # ...
 step Model(User, :create)
 step Policy::Pundit(User::Policy, :create?)
 step Contract::Build()
 step Contract::Validate(representer: User::Representer::In::Default)
 step :set_person
 # ...

 def set_person(options, **)
   person = Person.find(options['contract.default'].person.id)
   options['contract.default'].person = person
 end

关于ruby - User#firstname委托(delegate)给person.firstname,但person为nil,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47434883/

10-13 04:51