You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何适配Spyke模型?如何扩展User模型支持user.company.name?

How to Add Support for user.company.name in Your Spyke User Model

Hey there! Let's get your Spyke User model set up to handle nested company.name calls smoothly. There are two clean approaches you can take depending on your needs:

Since company is a nested resource tied to a user, the most idiomatic way in Spyke is to create a dedicated Company model and link it via a has_one association. This keeps your code organized and aligns with Spyke's resource-oriented design.

First, create a Company model:

class Company < Spyke::Base
  attributes :name
  # Add any other company attributes your API returns here
end

Then update your existing User model to include the association:

class User < Spyke::Base
  attributes :name, :email, :phone, :password, :errors
  has_one :company
end

That's it! If your API returns a JSON structure where the user object includes a nested company object (like below), Spyke will automatically instantiate a Company instance for you:

Example API response snippet:

{
  "user": {
    "name": "Jane Doe",
    "email": "jane@example.com",
    "company": {
      "name": "Tech Corp Inc."
    }
  }
}

You can now call user.company.name directly to access the company's name.

2. Define a Nested company Attribute (No Separate Model)

If you don't want to create a separate Company model, you can simply add :company to your User's attributes and access the nested name directly. This works if you only need to read the company name and don't need additional company-related logic.

Update your User model like this:

class User < Spyke::Base
  attributes :name, :email, :phone, :password, :errors, :company

  # Optional: Add a helper method for safer access (handles nil company cases)
  def company_name
    company&.fetch(:name, nil)
  end
end

With this setup, you can either call user.company[:name] or use the helper method user.company_name to get the company name.

Both methods will let you access the nested company name—pick the one that fits how you plan to work with company data long-term!

内容的提问来源于stack exchange,提问作者Hatem Khattab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:12:28