Rails 首先或通过一个值初始化,但如果创建则添加更多值 [英] Rails first or initialize by one value, but add more values if created

查看:23
本文介绍了Rails 首先或通过一个值初始化,但如果创建则添加更多值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以以下为例:

GroupMember.where(:member_id => 4).first_or_initialize

如果我想说这样的话怎么办-

What if I wanted to say something like this-

如果存在 member_id 为 4 的 GroupMember,找到它".否则,创建一个成员 ID 为 4 且 group_id 为 7 的 GroupMember.

If GroupMember with a member_id of 4 exists, "find it". Otherwise, create a GroupMember with the member_id of 4 AND a group_id of 7.

所以我希望上面的语句只检查 member_id - 但如果它不存在,我希望它创建一个具有多个属性的 GroupMember.我该怎么写?我使用的是 Rails 4.0.

So I want the above statement to only check for the member_id - But if it doesn't exist, I want it to create a GroupMember with multiple attributes. How would I write that? I am using rails 4.0.

推荐答案

这是我使用的参考 - http://apidock.com/rails/ActiveRecord/Relation/first_or_initialize

This is the reference I use - http://apidock.com/rails/ActiveRecord/Relation/first_or_initialize

该方法的来源说明:

def first_or_initialize(attributes = nil, &block)
  first || new(attributes, &block)
end

因此,如果未找到该记录 - 它会初始化一个新记录并传递给一个块.

So, if the record is not found - it initialises a new one and passes to a block.

你可以使用它:

GroupMember.where(:member_id => 4).first_or_initialize do |member|
  member.group_id = 7
end

它只会对新记录执行块.

It will execute block for new record only.

这篇关于Rails 首先或通过一个值初始化,但如果创建则添加更多值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆