gpt4 book ai didi

ruby-on-rails - 无法批量分配 protected 属性 : tags_attributes?

转载 作者:行者123 更新时间:2023-12-03 16:13:47 26 4
gpt4 key购买 nike

我正在尝试按照 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

View /帖子/_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 %>

View /标签/_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 %>

但是当我尝试创建标签时出现此错误:

Can't mass-assign protected attributes: tags_attributes Rails.root: /home/alex/rails/r7

Application Trace | Framework Trace | Full Trace app/controllers/posts_controller.rb:25:in `create' Request

Parameters:

{"utf8"=>"✓", "authenticity_token"=>"VF/qlfZ4Q5yvPY4VIbpFn65hoTAXdEa4fb4I1Ug4ETE=", "post"=>{"title"=>"post number 5", "content"=>"post number 5 post number 5 post number 5", "tags_attributes"=>{"0"=>{"name"=>"food, drinks"}}}, "commit"=>"Create Post"}



有什么建议可以解决这个问题吗?

最佳答案

只需放置 :tags_attributes 而不是 :tags 。请引用以下。这将解决我面临的同样问题

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

关于ruby-on-rails - 无法批量分配 protected 属性 : tags_attributes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9441819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com