Rails属性未保存

时间:2014-11-19 13:25:35

标签: ruby-on-rails ruby-on-rails-4

尝试使用AJAX调用保存新实体(Vote)时,但未分配属性。

正在使用的类和方法:

class VoteController < ApplicationController
    respond_to :json

    def vote
        question_id = params[:question][:id]
        user_id = current_user.id
        vote = Vote.where(["question_id = :q", { q: question_id }]).where(["user_id = :u", { u: user_id }]).take
        respond_with do |format|
            if vote.nil?
                @vote = Vote.new
                @vote.question = question_id
                @vote.user = user_id
                @vote.save
                format.json { render :json => { :status => 'ok' } }
            else            
                format.json { render :json => { :status => 'failed', :msg => 'You already voted' } }
            end
        end
    end
end

模特:

class Vote < ActiveRecord::Base
    belongs_to :user
    belongs_to :question

    attr_accessor :user, :question
end

迁移:

class CreateVotes < ActiveRecord::Migration
  def change
    create_table :votes do |t|
        t.references :question
        t.references :user
    end
  end
end

这些是正在发送的参数:

Parameters: {"utf8"=>"✓", "question"=>{"id"=>"1"}, "commit"=>"Up vote"}

使用puts我测试current_user.id确实返回一个值。

这里执行的查询:

INSERT INTO `votes` VALUES ()

我在数据库中的记录:

+----+-------------+---------+
| id | question_id | user_id |
+----+-------------+---------+
|  1 |        NULL |    NULL |
|  2 |        NULL |    NULL |
|  3 |        NULL |    NULL |
|  4 |        NULL |    NULL |
|  5 |        NULL |    NULL |
|  6 |        NULL |    NULL |
|  7 |        NULL |    NULL |
+----+-------------+---------+

为什么不分配这些属性?

1 个答案:

答案 0 :(得分:1)

因为attr_accessor :user, :question是&#34;掩盖&#34; ActiveRecord的同名方法。删除该行,然后重试。