ruby 嵌套函数
Relationships can be very messy. Ideally they they are clean and make us happy, but rarely does that actually come to pass. Especially when you have a single table that acts as a lynchpin in your data structure, Rails has a solution for you: nested attributes. This relationship is remarkably easy to implement, once you know where to put the various pieces. So let’s get to unifying our tables with nested relationships!
关系可能非常混乱。 理想情况下,它们很干净并使我们感到高兴,但实际上很少能实现。 尤其是当您有一个表充当数据结构的关键时,Rails为您提供了一个解决方案:嵌套属性。 一旦您知道将各个部分放在哪里,这种关系就非常容易实现。 因此,让我们开始使用嵌套关系来统一我们的表!
First, we’ll need a project with two models. In this case we’ll go ahead and use Rails to get us up and running quickly. Once your file is started, go ahead and run the following in your project directory terminal:
首先,我们需要一个具有两个模型的项目。 在这种情况下,我们将继续使用Rails来使我们快速启动并运行。 文件启动后,继续在项目目录终端中运行以下命令:
rails g scaffold User first_name last_nameFollowed by:
其次是:
rails g model Address street city state zip:integer user:referencerails db:migrateThis will build out a User with all of our routes, controller, and model, and a model for our Address. Next we’ll go into the model file for both of these, starting with User.
这将使用我们的所有路线,控制器和模型以及我们的地址模型来构建一个User。 接下来,我们将从User开始进入这两个模型文件。
class User < ApplicationRecord has_one :address, dependent: :destroy accepts_nested_attributes_for :address, allow_destroy: trueendThis sets up our User class to be able to do full CRUD with address. Next inside of Address model:
这将设置我们的User类,使其能够使用地址执行完整的CRUD。 地址模型的下一个内部:
class AbilityScore < ApplicationRecord belongs_to :characterendNow we just need to head over to users_controller.rb and finish up the last of the magic. With scaffold you should already have all your CRUD methods and strong params established, so now we’ll just add our relationship to the Address class. Anywhere where you are rendering back the json of User, add an includes for Address.
现在我们只需要转到users_controller.rb并完成最后的魔术。 使用脚手架,您应该已经建立了所有的CRUD方法和强大的参数,因此现在我们只需将关系添加到Address类即可。 在要呈现User json的任何地方,为Address添加一个include。
# GET /usersdef index @users = User.all render json: @users, include: [:address]end# GET /users/1def show render json: @user, include: [:address]end# POST /usersdef create @user = User.new(user_params) if @user.save render json: @user, include: [:address], status: :created, location: @user else render json: @user.errors, status: :unprocessable_entity endend# PATCH/PUT /users/1def update if @user.update(user_params) render json: @user, include: [:address] else render json: @user.errors, status: :unprocessable_entity endendAnd finally under the private heading for our user_params we’ll need to allow address attributes.
最后,在user_params的专用标题下,我们需要允许地址属性。
# Only allow a trusted parameter "white list" through.def character_params params.require(:character).permit( :first_name, :last_name, address_attributes: [:id, :street, :city, :state, :zip, :user_id] )endAt this point you can use a service like Postman to do full CRUD actions with only User calls. However, the includes sends the address key, not the address_attributes key. So the strong params will not allow the data back until that key has been mutated. The following code would work for a POST request, creating both a User and an associated address. (Formatted for Postman)
此时,您可以使用Postman之类的服务仅通过用户调用来执行完整的CRUD操作。 但是,includes发送地址密钥,而不发送address_attributes密钥。 因此,强参数将不允许数据返回,直到该键已被突变。 以下代码适用于POST请求,同时创建用户和关联地址。 (为邮递员格式化)
{ “first_name”: “Montague”, “last_name”: “Guyari”, “address_attributes”: { “street”: “234 Somewhere Lane”, “city”: “Neverland”, “state”: “Nevada”, “zip”: 93347 }}And this would work for an PATCH request:
这将适用于PATCH请求:
{ "id": 3, "first_name": "Montague", "last_name": "Guyari", "address_attributes": { "id": 5, "street": "234 Somewhere Lane", "city": "Neverland", "state": "Nevada", "zip": 93347, "user_id": 3 }}And this would be the result of a GET request:
这将是GET请求的结果:
{ "id": 3, "first_name": "Montague", "last_name": "Guyari", "address": { "id": 5, "street": "234 Somewhere Lane", "city": "Neverland", "state": "Nevada", "zip": 93347, "user_id": 3 }}If you were hoping to unify your data using nested attributes I hope this helped set you on the path to functional code! This is a great way of keeping your data organized and could even help make less requests for data in the long run. While it does have some quirks, namely needing to add _attributes to your nested return keys, overall the implementation is not hard!
如果您希望使用嵌套属性来统一数据,希望这有助于您踏上功能代码的道路! 从长远来看,这是使数据井井有条的好方法,甚至可以减少对数据的请求。 尽管它确实有一些怪癖,即需要在嵌套的返回键中添加_attributes,但总体上实现起来并不难!
翻译自: https://medium.com/@lrmcguire93/nested-attributes-ruby-on-rails-db2fcc5aa95c
ruby 嵌套函数
