Rails属性不更新

时间:2016-05-15 00:01:53

标签: ruby-on-rails-3 attributes

我正在构建一个邀请系统,用户可以邀请朋友,将他们的user.id设置为数据库中的sender字段,或者请求邀请,该邀请应设置{{1 }到'0'(整​​数字段)。

用户模型

sender

邀请模式

...
has_many :invites, :class_name => 'Invitation', :foreign_key => 'sender' #sent_invitations
belongs_to :invitation
...

邀请控制器

belongs_to :sender, :class_name => 'User'
has_one :recipient, :class_name => 'User'

正在创建邀请(我可以在数据库中看到它),但未设置发件人。这是dev_log:

的输出形式
def create
    @invitation = Invitation.new(invitation_params)
    if current_user?
      @invitation.sender = current_user
      if @invitation.save
        redirect_to invitations_url, notice: 'Thank you. Your invitation has been sent.'
      else
        render action: "new"
      end
    else
      @invitation.sender = 0
      if @invitation.save
        redirect_to invitations_url, notice: 'Thank you. You request is being processed..'
      else
        render action: "new"
      end
    end
  end

我很难过,因为#1,我没有创建任意属性“sender_id”。数据库中适用的列是“sender”,#2,POST没有设置Started POST "/invitations" for 127.0.0.1 at 2016-05-14 17:49:54 -0600 Processing by InvitationsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"aCasBmkfw0m1T/EwuBUlXTA/z+REEWo3Hpv2HpB9w6s=", "invitation"=>{"name"=>"john", "surname"=>"public", "recipient_email"=>"jp@sasdf.com"}, "commit"=>"Create Invitation"} User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."auth_token" = 'i__MG0iqyoIND68k6qJmvw' LIMIT 1 DEPRECATION WARNING: You're trying to create an attribute `sender_id'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer` etc. (called from create at C:/Sites/template/app/controllers/invitations_controller.rb:38) (0.0ms) begin transaction User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'jp@sasdf.com' LIMIT 1 SQL (1.0ms) INSERT INTO "invitations" ("created_at", "invite_token", "name", "recipient_email", "sender", "sent_at", "surname", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?) [["created_at", Sat, 14 May 2016 23:49:55 UTC +00:00], ["invite_token", "m_1zd0UxW3W1JqoDdp1EMA"], ["name", "john"], ["recipient_email", "jp@sasdf.com"], ["sender", nil], ["sent_at", nil], ["surname", "public"], ["updated_at", Sat, 14 May 2016 23:49:55 UTC +00:00]] (0.0ms) UPDATE "users" SET "invites_avail" = 4, "updated_at" = '2016-05-14 23:49:55.161966' WHERE "users"."id" = 2 (70.0ms) commit transaction Redirected to http://localhost:3000/invitations Completed 302 Found in 193.0ms (ActiveRecord: 76.0ms) id,它应该是“0”或current_user的id。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我无法找到我的问题的答案,所以我把它变成了猴子。

由于我从invitation.sender发送邀请时能够保存current_user,其余的只是在数据库中设置任何内容(NULL),我更改了invitations_controller.rb中的查询参数,以查找所有公司发送的邀请的@invitation.sender = nil

除非有人发布更好的回复,否则我会把它留下来。干杯!