【问题标题】:Get id form another table, rails从另一个表获取 id,rails
【发布时间】:2013-04-19 01:09:56
【问题描述】:

我有一个包含“user_id”和“post_id”字段的表测试。 user_id 我通过 current_user.id 和 post_id 从 post 表中获取。为此,我这样做: 在测试控制器中:-

def create
  @user = current_user
  @test = Test.new(params[:test])
  @post = Post.find(params[:id])
  @test.post_id = @post.id
  @test.user_id = @user.id
respond_to do |format|
   @test.save
   format.html { redirect_to(:back, :notice => "successfull") }
  else
    format.html { render :action => "new" }
  end
end

在我的模型中,我创建了关联:-

在 test.rb 中:

 belongs_to :post

在 post.rb 中:

has_many :test

查看页面是:

 = form_for @test, :validate => true do |f|
   .span
     = f.text_field :email, :placeholder =>"Email Address"
   .span
     = f.label :name
     = f.text_field :name
   .span
     = f.submit "Save"

user_id 保存正确,但 post_id 报错:

 Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

我该如何解决这个问题?

【问题讨论】:

  • 你确定你应该只在登录时访问create方法,即current_user不应该是nil

标签: ruby-on-rails associations


【解决方案1】:

Rails 中的标准消息是否告诉您您尝试在 nil 值上调用 .id

我怀疑你的 current_usernil。你可以通过raise current_user.inspect 确定,我想这会告诉你它为零

您确定您已登录,因此您的current_user 不为零

【讨论】:

  • 嘿@bilash,由于post_id没有保存在我的测试表中,它无法从post表中获取post id。当用户登录时,current_user没有问题。请帮助如果你有什么想法。感谢您的回复。
【解决方案2】:

您确定只有在登录时才应该访问 create 方法,即 current_user 不应为 nil。

如果您只在create 方法中收到此错误,那么它应该在线

@test.user_id = @user.id

这是因为@user 为零,而您在nil 上调用.id

已编辑

假设您在 @post 中获取 post 对象,您需要从表单中发送 post_id

添加以下行您的视图

= form_for @test, :validate => true do |f|
    = hidden_field_tag "post_id", @post.id

并更新

@post = Post.find(params[:id])

@post = Post.find(params[:post_id])

【讨论】:

  • 嘿@Salil 感谢您的回复..有关 current_user 的问题,因为此操作仅在用户登录时使用。主要问题是,我无法保存 post_id跨度>
  • 您是说@postnil 但事实并非如此,因为@post = Post.find(params[:id]) 中的find 方法会抛出类似Cannot find Post with id ### 的错误,所以只需检查您的ID 是否正确正如current_user 应该not be nil
  • 抱歉,此消息显示在浏览器上。[找不到没有 ID 的帖子]
  • 这意味着你在你的 url 中提供了错误的 id,或者你传递给用户的初学者的常见错误是并找到使用它的帖子。所以,你必须找出你是否提供了正确的 id
  • 我有一个 post 表,我正在从该表中获取 id,并且我已经使用 Post.find(params[:id]) 和 Post.find(params[:post_id]) 检查了 id ,但两者都不适合我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多