3

我在这里阅读了很多帖子,但仍然无法弄清楚这一点。

我有一个 forum_post 模型和一个 links 模型。我想将链接表单与 forum_post 表单嵌套,但不断获得 Can't mass-assign protected attributes: links。

论坛帖子模型

class ForumPost < ActiveRecord::Base
  attr_accessible :content, :links_attributes

  has_many :links, :as => :linkable, :dependent => :destroy

  accepts_nested_attributes_for :links, :allow_destroy => true
end

链接模型

class Link < ActiveRecord::Base
  attr_accessible :description, :image_url, :link_url, :linkable_id, :linkable_type, :title

  belongs_to  :linkable, :polymorphic => true
end

Forum_post 查看

<%= form_for(@forum_post) do |f| %>
  <% if @forum_post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@forum_post.errors.count, "error") %> prohibited this forum_post from being saved:</h2>

      <ul>
      <% @forum_post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_area :content, :rows => 5 %>
  </div>

  <%= f.fields_for :link do |link| %>
   <%= render :partial => 'links/link', :locals => { :f => link} %>
  <% end%>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

链接查看部分

<div class="field">
  <%= f.label :link_url %><br />
  <%= f.text_field :link_url, :id => "url_field" %>
</div>

<div id="link_preview">
</div>

论坛帖子控制器

class ForumPostsController < ApplicationController

    def new
    @forum_post = ForumPost.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @forum_post }
    end

   def create
     @forum_post = ForumPost.new(params[:forum_post])

     respond_to do |format|
     if @forum_post.save
       format.html { redirect_to @forum_post, notice: 'Forum post was successfully created.' }
       format.json { render json: @forum_post, status: :created, location: @forum_post }
    else
      format.html { render action: "new" }
      format.json { render json: @forum_post.errors, status: :unprocessable_entity }
    end
  end
end

链接控制器

class LinksController < ApplicationController

    def find_linkable
    params.each do |name, value|
      if name =~ /(.+)_id$/
        return $1.classify.constantize.find(value)
      end
    end
    nil
  end

  def index
    @linkable = find_linkable
    @links = @linkable.links
  end

  def create
    @linkable = find_linkable
    @link = @linkable.links.build(params[:link])
    if @link.save
      flash[:notice] = "Successfully saved link."
      redirect_to :id => nil
    else
      render :action => 'new'
    end
  end

end
4

1 回答 1

1

好吧,根据您的问题,您无法批量分配的受保护属性是:链接。不知道这是怎么发生的,但你试过 attr_accessible :links 吗?

至于安全隐患,这就是 github 被黑客入侵一次https://gist.github.com/1978249的原因,我强烈反对将 whitelist_attributes 设置为 false。

于 2012-12-10T01:00:50.990 回答