回答

0

如果模型定義,就像如下:

user.rb

class User < ActiveRecord::Base 
    attr_accessible :name, :posts_attributes 
    has_many :posts 
    accepts_nested_attributes_for :posts 
end 

post.rb

class Post < ActiveRecord::Base 
    attr_accessible :title, :content :user_id 
end 

然後一切應該沒問題。您可以將帖子保存爲嵌套屬性。

這裏是初學者:)

https://github.com/railscash/sample_change_user_role

0

質量分配是名稱的Rails給予的行爲用參數散列構造你的對象。這是「質量分配」,因爲您正在通過一個賦值運算符爲屬性分配多個值。

下面的代碼片段執行後模型的名稱和標題屬性的質量分配:

Post.new(:name => "John", :topic => "Something") 
Post.create(:name => "John", :topic => "Something") 
Post.update_attributes(:name => "John", :topic => "Something") 

爲了這個工作,你的模型必須允許質量分配在你的哈希每個屬性有傳入

在此將失敗兩種情況:

你有一個attr_accessible聲明不包括:姓名

您有一個attr_protected,其中包括:名稱

最近,默認情況下,屬性必須通過attr_accessible手動列入白名單,以便批量分配成功。在此之前,默認情況下屬性是可分配的,除非它們明確列入黑名attr_protected或其他任何屬性是用attr_acessible列出的。

相關問題