我正在尝试按照Rails Guide:
为帖子创建标签tag.rb:
class Tag < ActiveRecord::Base
attr_accessible :name
belongs_to :post
end
post.rb:
class Post < ActiveRecord::Base
attr_accessible :title, :content, :tags
validates :title, :presence => true,
:length => { :maximum => 30 },
:uniqueness => true
validates :content, :presence => true,
:uniqueness => true
belongs_to :user
has_many :comments, :dependent => :destroy
has_many :votes, :as => :votable, :dependent => :destroy
has_many :tags
accepts_nested_attributes_for :tags, :allow_destroy => :true,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end
视图/帖/ _form.html.erb:
<% @post.tags.build %>
<%= form_for(@post) do |post_form| %>
<%= render 'shared/error_messages' %>
<div class="field">
<%= post_form.label :title %><br />
<%= post_form.text_field :title %>
</div>
<div class="field">
<%= post_form.label :content %><br />
<%= post_form.text_area :content %>
</div>
<h2>Tags</h2>
<%= render :partial => 'tags/form',
:locals => {:form => post_form} %>
<div class="actions">
<%= post_form.submit %>
</div>
<% end %>
视图/标签/ _form.html.erb:
<%= form.fields_for :tags do |tag_form| %>
<div class="field">
<%= tag_form.label :name, 'Tag:' %>
<%= tag_form.text_field :name %>
</div>
<% unless tag_form.object.nil? || tag_form.object.new_record? %>
<div class="field">
<%= tag_form.label :_destroy, 'Remove:' %>
<%= tag_form.check_box :_destroy %>
</div>
<% end %>
<% end %>
但是当我尝试创建标记时出现此错误:
无法批量分配受保护的属性:tags_attributes Rails.root: /家庭/亚历克斯/轨道/ R7
应用程序跟踪|框架跟踪|完整追踪 app / controllers / posts_controller.rb:25:在'create'Request
中参数:
{ “UTF8”=&gt; “中✓”, “authenticity_token”=&gt; “中VF / qlfZ4Q5yvPY4VIbpFn65hoTAXdEa4fb4I1Ug4ETE =”, “post”=&gt; {“title”=&gt;“帖子编号5”,“内容”=&gt;“帖子编号5帖子 5号邮政编号5“,”tags_attributes“=&gt; {”0“=&gt; {”name“=&gt;”食物, 饮料“}}},”提交“=&gt;”创建帖子“}
有任何解决此问题的建议吗?
答案 0 :(得分:13)
只需输入:tags_attributes而不是:tags。请参考下文。这将解决我面临的问题
class Post < ActiveRecord::Base
attr_accessible :title, :content, :tags_attributes
end
答案 1 :(得分:6)
Attr_accessible指定您无法批量指定属性。 在这里,您还需要将post_id设为attr_accessible。 请参阅WARNING: Can't mass-assign protected attributes
答案 2 :(得分:6)
这对我有用:
class Post < ActiveRecord::Base
attr_accessible :name, :title, :content, :tags_attributes
end
答案 3 :(得分:1)
这也适合我:
class Post < ActiveRecord::Base
attr_accessible :title, :content, :tags_attributes
end
这允许您通过Post访问标签属性。