ActiveModel :: ForbiddenAttributesError仅使用params

时间:2015-08-17 21:02:32

标签: ruby-on-rails-4 activerecord rails-activerecord

我在创建操作中的第2行获得ActiveModel::ForbiddenAttributesError in MicropostsController#create

尝试将f.hidden_field更改为hidden_field_tag,但仍然获得ForbiddenAttributesError

micropost_controller

  def create
    tag = Tag.find(params[:micropost][:tag_id])
    @micropost = tag.microposts.build(params[:micropost])
    @micropost.user_id = current_user.id
    if @micropost.save
      flash[:success] = "Posted!"
      redirect_to root_path
    else
      render 'static_pages/home'
    end
  end

tags_controller

  def details
    @tag = Tag.find(params[:id])
    @microposts = @tag.microposts
    @micropost = @tag.microposts.build if sign_in?
  end

微博形式

<%= form_for(@micropost) do |f| %>
  <%= render 'shared/error_messages', object: @micropost %>
  <div class="field">
    <%=  f.text_area :content, placeholder: "Your post" %>
    <%=  f.hidden_field :tag_id %>
  </div>
  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

在tags.rb

  has_many :microposts, dependent: :destroy

在microposts.rb

  belongs_to :user
  belongs_to :tag

2 个答案:

答案 0 :(得分:0)

这个

def create
  tag = Tag.find(params[:micropost][:tag_id])
  #...
end

应该更改为

def create
  tag = Tag.find(params[:tag_id])
  #...
end

答案 1 :(得分:0)

您似乎需要从tag_id参数中删除microposts

tag = Tag.find(params[:micropost].delete(:tag_id))
@micropost = tag.microposts.build(params[:micropost])

如果不能解决问题,只需将参数列入白名单(无论如何都是好主意):

micropost_params = params.require(:micropost).permit(:name, :title, ...)
@micropost = tag.microposts.build(micropost_params)