我正在使用first_or_create填充電子郵件訂戶(稱爲成員)列表的表。代碼如下:Rails first_or_create!在數據庫表中創建空值
def community_members=(members)
self.members = members.split(",").map do |member|
Member.where(email: member.strip, community_id: self.id).first_or_create! unless member.strip == nil
end
end
一切正常,只是當我添加額外的電子郵件,以同一社區,表變成了「community_id」列所有以前的行爲NULL。
這裏的服務器日誌:
Member Load (0.2ms) SELECT "members".* FROM "members" WHERE "members"."email" = $1 AND "members"."community_id" = $2 ORDER BY "members"."id" ASC LIMIT 1 [["email", "[email protected]"], ["community_id", 1]]
SQL (0.3ms) INSERT INTO "members" ("email", "community_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["email", "[email protected]"], ["community_id", 1], ["created_at", "2015-04-30 16:14:25.930012"], ["updated_at", "2015-04-30 16:14:25.930012"]]
Member Load (0.2ms) SELECT "members".* FROM "members" WHERE "members"."community_id" = $1 [["community_id", 1]]
SQL (0.4ms) UPDATE "members" SET "community_id" = NULL WHERE "members"."community_id" = $1 AND "members"."id" = 30 [["community_id", 1]]
(0.3ms) COMMIT
第一個「會員」負荷不正是它應該做的。但由於某種原因,它總是以第二個成員加載結束,並將所有「community_id」字段設置爲NULL。
現在我打電話:community_member從形式的社區頁面上:
<%= form_for(@community) do |f| %>
<%= f.text_area :community_members, class:"form-control input-lg", placeholder:"Please add your list of comma separated member email addresses here" %>
<%= f.submit "Save", class: "btn btn-lg btn-green btn-block pad-top" %>
<% end %>
好像我缺少明顯的東西在這裏。有任何想法嗎?謝謝。
你可以刪除!從first_or_create !,我想community_members函數是在社區模型中。你可以在保存社區對象之前在模型中創建它。 – coderhs
我嘗試刪除!並沒有什麼區別。在添加任何成員之前,社區對象已經存在,所以我認爲它不需要保存? – Lorenz