简体   繁体   English

从另一张表中获取id,rails

[英]Get id form another table, rails

I have a table test having fields 'user_id' and 'post_id'. 我有一个表测试,其中包含字段'user_id'和'post_id'。 user_id I fetch by current_user.id and post_id from the post table. user_id我从post表中获取current_user.id和post_id。 For this I do: In test controller:- 为此我做:在测试控制器: -

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

In my Models, I create association:- 在我的模型中,我创建了关联: -

In test.rb: 在test.rb中:

 belongs_to :post

In post.rb: 在post.rb中:

has_many :test

The View page is: 查看页面是:

 = 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"

The user_id save properly but for post_id it give error: user_id正确保存,但对于post_id,它会给出错误:

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

How can I resolve that problem ? 我该如何解决这个问题?

Are you sure you should access the create method only when you are login ie current_user should not be nil. 您确定只有在登录时才应访问create方法,即current_user不应为nil。

If you are getting this error in create method only then it should be on line 如果您只在create方法中遇到此错误,那么它应该在线

@test.user_id = @user.id

this is because @user is nil, and you are calling .id on nil . 这是因为@user是nil,你在nil上调用.id

EDITED EDITED

You need to send post_id from your form, assuming you are getting post object in @post 假设您在@post中获得post对象,则需要从表单发送post_id

Add following line your view 在视图中添加以下行

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

and update 并更新

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

with

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

Is the standard message in Rails that tells you that you tried to invoke .id on a nil value. Rails中的标准消息是否告诉您尝试在nil值上调用.id

I suspect your current_user is nil . 我怀疑你的current_usernil You can be sure by raise current_user.inspect i think which will tell you that its nil 你可以肯定通过raise current_user.inspect我认为哪个会告诉你它的零

You be sure you are logged in so that your current_user is not nil 您确定已登录,因此您的current_user不是零

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM