這裏有幾個問題,coverthisalready,我知道。我是編程和導軌的新手,所以請耐心等待。我的目標是收集n
標記對象並將它們顯示在我的顯示和索引操作中。質量分配屬性以嵌套形式失敗。無聲錯誤?
UPDATE 感謝所有回答的傢伙。每個建議都促使我朝着正確的方向發展。我可以通過傳入一個空數組來初始化tags
對象來獲取rake任務來創建帖子。但是標籤仍然沒有創建。在進一步的檢查,我得到以下SQL異常:
irb(main):002:0> u.posts.build(title: "a new day", tags: "jump")
WARNING: Can't mass-assign protected attributes: tags
(1.7ms) SELECT 1 FROM "posts" WHERE "posts"."title" = 'a new day' LIMIT 1
(0.5ms) COMMIT
=> #<Post id: nil, title: "a new day", description: nil, content: nil, user_id: 1, created_at: nil, updated_at: nil>
我的設立如下:
Tag
型號
class Tag < ActiveRecord::Base
belongs_to :post
end
Post
型號
class Post < ActiveRecord::Base
has_many :tags, autosave: true
attr_accessible :title, :description, :content, :tags_attributes
accepts_nested_attributes_for :tags, allow_destroy: true, reject_if: lambda {|attrs| attrs.all? {|key, value| value.blank?}}
#add n number of form fields to capture tags in each article.
def with_blank_tags(n = 3)
n.times do
tags.build
end
self
end
end
'查看' 代碼
<%= form_for(@post.with_blank_tags) do |f| %>
<div class="field">
<%= f.fields_for(:tags) do |tags| %>
<%= unless tags.object.new_record? tags.check_box('_destroy') + tags.label('_destroy', 'Remove Tag') end%>
<%= tags.label :tags, "Add a Tag"%>
<%= tags.text_field :tags %>
<%end%>
</div>
<%end%>
「控制」的代碼
def new
@post = @user.posts.build
end
def create
@post = @user.posts.build(params[:post])
if @post.save?
respond_to do |format|
format.html { redirect_to @post, notice: 'Post was successfully created.' }
else
format.html { render action: :new }
end
end
end
我的耙子任務:
3210
如果這件事情我會很驚訝。但是到目前爲止,web上看到的很多其他問題和示例都有在attr_accessible調用之前調用了接受嵌套屬性。可能需要在將#{name} _attributes白名單列出之前進行定義? – agmcleod 2012-01-11 18:58:55
@agmcleod我按照您建議的順序發出了呼叫,並收到相同的異常。 – rhodee 2012-01-11 19:06:15
@agmcleod我在這個[post](http://stackoverflow.com/questions/2792622/what-does-this-rake-dbseed-error-mean)中遇到了一個解決方案,建議重新命名模型。我想知道模型的名稱標籤是不可接受的嗎? – rhodee 2012-01-11 19:10:34