2013-10-23 17 views
2

我遇到了一個問題,最近使用ActiveRecord放置在一個表上。這是最初的遷移創建表:Post.create方法不正確的參數個數(3爲2)

class CreatePosts < ActiveRecord::Migration 
    def change 
    create_table :posts do |t| 
     t.string :title 
     t.text :content 

     t.timestamps 
    end 
    end 
end 

我添加一個字段,它後來與此遷移:

class AddPrivateToPosts < ActiveRecord::Migration 
    def change 
    add_column :posts, :private, :boolean 
    end 
end 

每當我打電話Post.create("Title", "Content", true)Post.create!("Title", "Content", true),我得到too many arguments錯誤。任何人都可以幫助我嗎?

回答

2

您應該將包含您所需屬性的散列傳遞給Post.create,例如, Post.create(title: 'title', content: 'content', private: true)

Ruby函數調用總是以參數散列結束,並且可以省略散列符號{ }。在這種情況下,散列被傳遞給create的第一個參數,即屬性散列。或者,您可以顯式地傳遞哈希值,然後將更多哈希類型的參數傳遞給第二個參數options,例如,

Post.create({title: 'title', ...}, without_protection: true)

API參考herehere

+0

這個工作。謝謝 - 不知道這是rails語法的一部分。 – Nick

相關問題