2013-04-25 48 views
0

我有一個表格測試,其中包含字段'user_id'和'post_id'。 user_id我從帖子表中通過current_user.id和post_id獲取。爲此,我做的事: 在測試控制器: -獲取身份證表格另一個表格,導軌

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 

我怎樣才能解決這個問題?

+0

你確定你應該只當你訪問'create'方法是登錄即'current_user'不應爲零 – Salil 2013-04-25 08:23:13

回答

1

您確定只有在您登錄後才能訪問create方法,即current_user不應該爲零。

如果您收到在create方法這個錯誤才應該對線

@test.user_id = @user.id 

這是因爲@user爲零,而你正在呼籲nil.id

EDITED

您需要從您的形式發送POST_ID,假設你得到後對象@post

添加以下行您的看法

= 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]) 
+0

嗨@Salil感謝您的回覆..有關於current_user的問題,因爲此操作僅在用戶使用時才使用。主要問題是,我無法保存post_id – Rajeev 2013-04-25 09:37:25

+0

你在說'@ post'是'nil',但情況並非如此,因爲'@post = Post'中的'find'方法。find(params [:id])'會拋出錯誤,如'無法找到帶ID的郵件###'所以只檢查您的ID是否正確以及'current_user'應該'不是無' – Salil 2013-04-25 09:42:51

+0

對不起,此消息顯示[無法找到沒有ID的帖子] – Rajeev 2013-04-25 09:49:51

1

Rails中的標準消息告​​訴您,您試圖調用.id上的nil值。

我懷疑你的current_usernil。您可以通過raise current_user.inspect可以肯定,我認爲它會告訴你,它的零

你確保你登錄,這樣你的current_user不是零

+0

嘿@bilash,發生因post_id不保存在我的測試表中,它無法從發佈表中獲取發佈ID。當用戶登錄時沒有current_user的問題。如果您有任何想法,請點擊幫助。感謝您的迴應。 – Rajeev 2013-04-25 09:43:28