Ruby-on-rails Rails 首先或通过一个值初始化,但如果创建则添加更多值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21190339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails first or initialize by one value, but add more values if created
提问by Luigi
Take the following for example:
以以下为例:
GroupMember.where(:member_id => 4).first_or_initialize
GroupMember.where(:member_id => 4).first_or_initialize
What if I wanted to say something like this-
如果我想说这样的话怎么办——
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 为 4 的 GroupMember,则“找到它”。否则,创建一个成员 ID 为 4 且 group_id 为 7 的 GroupMember。
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.
所以我希望上面的语句只检查 member_id - 但如果它不存在,我希望它创建一个具有多个属性的 GroupMember。我该怎么写?我正在使用导轨 4.0。
回答by scottb
This also works:
这也有效:
GroupMember.where(member_id: 4).first_or_initialize(group_id: 7)
The attributes passed to first_or_initialize are only used when it creates the new record, and they're merged with the attributes from the "where" clause.
传递给 first_or_initialize 的属性仅在创建新记录时使用,并且它们与来自“where”子句的属性合并。
回答by Nikita Chernov
This is the reference I use - http://apidock.com/rails/ActiveRecord/Relation/first_or_initialize
这是我使用的参考 - http://apidock.com/rails/ActiveRecord/Relation/first_or_initialize
The method's source states:
该方法的来源指出:
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.
因此,如果未找到该记录 - 它会初始化一个新记录并传递给一个块。
You can use it:
你可以使用它:
GroupMember.where(:member_id => 4).first_or_initialize do |member|
member.group_id = 7
end
It will execute block for new record only.
它只会为新记录执行块。
回答by Rubyist
Using
使用
find_or_initialize_by_member_id_and_group_id(member_id, group_id)
you will create GroupMember uniq both by member_id and group id. (by is used only once)
您将通过 member_id 和组 ID 创建 GroupMember uniq。(by 只使用一次)
I am not sure this statement will work on Rails 4 or not. It is working on Rails 3.2
我不确定这个声明是否适用于 Rails 4。它正在使用 Rails 3.2
Please check the above statement at rails console and let me know if it works on not.
请在 rails 控制台检查上述声明,如果它不起作用,请告诉我。
Update:
更新:
As per the error console code has to be :
根据错误控制台代码必须是:
GroupMember.find_or_initialize_by(member_id: member_id, group_id: group_id )
Please verify the change works or not
请验证更改是否有效
回答by Nitin Jain
try with this
试试这个
Post.find_or_create_by(member_id: member_id, group_id: group_id )

