Rails first_or_create!在数据库表中创建空值

时间:2015-04-30 16:24:07

标签: mysql ruby-on-rails postgresql

我正在使用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", "lisa@holy.com"], ["community_id", 1]]
  SQL (0.3ms)  INSERT INTO "members" ("email", "community_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["email", "lisa@holy.com"], ["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 %>

好像我在这里遗漏了一些明显的东西。有任何想法吗?谢谢。

0 个答案:

没有答案