开发者

Rails - How to use find or create with a default value

开发者 https://www.devze.com 2023-02-28 02:46 出处:网络
I currently have the following: conversation_participation = @user.conversation_participations.find_or_create_by_conversation_id(conversation.id)

I currently have the following:

    conversation_participation = @user.conversation_participations.find_or_create_by_conversation_id(conversation.id)

This correctly creates a record, problem is the default value of conversation.read is false.

In this particular method I want the default value to be true when creating the record. Right now the only way I got this to work was by the following:

    conversation_participation = @user.conversation_participations.find_or_create_by_conversation_id(conversation.id)
    conversation_participation.read = true
    conversation_participation.save

Problem is this hits the DB twic开发者_Go百科e. How can I use find_or_create and set the default :read => true?

Thanks


You can try find_or_initialize_by...

Then set your read attribute as normal

conversation_participation = @user.conversation_participations.find_or_initialize_by_conversation_id(conversation.id)
conversation_participation.read = true
conversation_participation.save

Or

conversation_participation = @user.conversation_participations.find_or_initialize_by_conversation_id_and_read(conversation.id, true)
conversation_participation.save

With after_initialize (Oh.. you deleted your comment, but here is something for that just in case)

class Conversation < ActiveRecord::base
  def after_initialize
    self.read ||= true # true if not already set
  end
end

Then you can do find_or_create|initialize_by... or which ever way you wish to proceed.

More on callbacks if you are interest.


From here:

Use the find_or_initialize_by_ finder if you want to return a new record without saving it first.

So something like this:

conversation_participation = @user.conversation_participations.find_or_initialize_by_conversation_id(conversation.id)
conversation_participation.read = true
conversation_participation.save

This should just do an INSERT instead of an INSERT followed by an UPDATE.


Try this:

conversation_participation = @user.conversation_participations.find_or_create_by_conversation_id_and_read(conversation.id, true)
0

精彩评论

暂无评论...
验证码 换一张
取 消