这里有几个问题,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