【问题标题】:Rails .save() Doesn't Store IdRails .save() 不存储 ID
【发布时间】:2011-03-10 07:00:50
【问题描述】:

我正在 Rails 中编写一个 RESTful API,当我创建一个 Label 对象并使用 .save() 方法时,标签已正确保存到数据库中,但调用 @label.id 返回 null。

puts 语句验证除了 id 字段之外的所有内容都是正确的。我还验证了数据库具有正确的 ID。

另请注意:这是在嵌套资源 URL 内:POST /members/:member_id/labels/

以前有人经历过吗?

def create
  if params[:member_id] and params[:title]

    # Periods in a username will have been translated to underscores
    member_id = params[:member_id].gsub('_', '.')
    title = params[:title]

    # @member = Member.find(member_id) # No longer in use
    @label = Label.new(:username => member_id, :title => title)

    if @label.save

      puts " *** label: #{@label.inspect}"
      @label.reload

      respond_to do |format|
        format.json { render :json => @label, :status => :created and return }
      end
    else
      respond_with :status => 406, :errors => @label.errors and return
    end

  end

  respond_with :status => 406, :errors => [ :message => "member_id and title parameters must be provided" ] and return
end

很遗憾,我无法按照要求提供迁移文件,因为我正在连接到最初通过 PHP 查看的现有 PostgreSQL 数据库。但是,下面是 create table 语句以及 select * 的样子。

DROP TABLE student_labels;
CREATE TABLE student_labels (
  id serial not null,
  username text not null,
  title text not null,
  created_at timestamp not null default now(),
  updated_at timestamp not null default now(),
  deleted_at timestamp
);
发展=> 从学生标签中选择 *; 编号 |用户名 |标题 | created_at |更新时间 |删除_at ----+------------+--------------+-------- ---------+----------------------------+--------- - 7 | F0003 |繁荣 | 2011-03-10 05:49:06.01771 | 2011-03-10 05:49:06.01771 | 8 | F0003 |繁荣 | 2011-03-10 05:49:28.659 | 2011-03-10 05:49:28.659 | 9 | F0003 |繁荣 | 2011-03-10 05:52:03.343815 | 2011-03-10 05:52:03.343815 | 10 | F0003 |繁荣 | 2011-03-10 05:53:07.803489 | 2011-03-10 05:53:07.803489 |

【问题讨论】:

  • 你的意思是使用"label: #{@label.inspect}"?因为从我看到的非实例变量label 不存在?
  • 我认为@label.reload 不是必需的。检查您的数据库条目。是的,您的 puts 语句具有不存在的“标签”。
  • 你能告诉我们标签表的迁移吗?
  • @nzifnab - 确实,我的意思是@label.inspect,更新了代码以反映这一点。 @ashnish - 据我所知,@label.reload 不应该是必需的,有人建议我尝试一下。 @Chirantan - 添加了 SQL 信息,最初是用 PHP 完成的,所以没有迁移文件。

标签: ruby-on-rails json postgresql


【解决方案1】:

问题是您的id 列不是主键,因此当数据库请求最后插入行的id 时,它不知道要给rails 什么。

【讨论】:

  • +1 - 非常感谢您的帮助!我不敢相信我错过了……虽然,当我工作的时候是凌晨 1:00 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 2019-05-20
相关资源
最近更新 更多