gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:44:17 25 4
gpt4 key购买 nike

我正在使用 simple_form,我只想使用分类表在类别和文章之间创建关联。

但是我有这个错误:无法批量分配 protected 属性:category_ids。app/controllers/articles_controller.rb:36:in `update'

articles_controller.rb

def update
@article = Article.find(params[:id])
if @article.update_attributes(params[:article]) ---line with the problem
flash[:success] = "Статья обновлена"
redirect_to @article
else
render :edit
end
end

article.rb

has_many :categorizations
has_many :categories, through: :categorizations

category.rb

has_many :categorizations
has_many :articles, through: :categorizations

categorization.rb

belongs_to :article
belongs_to :category

分类有 article_id 和 category_id 字段。

我的 _form.html.erb

<%= simple_form_for @article, html: { class: "form-horizontal", multipart: true } do |f| %>
<%= f.error_notification %>
<%= f.input :title %>
<%= f.association :categories %>
<%= f.input :teaser %>
<%= f.input :body %>
<%= f.input :published %>
<% if @article.published? %>
<%= f.button :submit, value: "Внести изменения" %>
<% else %>
<%= f.button :submit, value: "Опубликовать" %>
<% end %>
<% end %>

最佳答案

你在 article.rb 中有 attr_accessible 吗?

如果是这样添加

     attr_accessible :title, :category_ids

还要确保您真的希望所有表单都使用此功能...如果不添加此功能:

  attr_accessible :title, :category_ids, :as => :admin

然后

@article = Article.new
@article.assign_attributes({ :category_ids => [1,2], :title => 'hello' })
@article.category_ids # => []
@article.title # => 'hello'

@article.assign_attributes({ :category_ids => [1,2], :title => 'hello' }, :as => :admin)
@article.category_ids # => [1,2]
@article.title # => 'hello'
@article.save

@article = Article.new({ :category_ids => [1,2], :title => 'hello' })
@article.category_ids # => []
@article.title # => 'hello'

@article = Article.new({ :category_ids => [1,2], :title => 'hello' }, :as => :admin)
@article.category_ids # => [1,2]
@article.title # => 'hello'
@article.save

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

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