3
我已經閱讀了大量的帖子,但仍無法確定這一點。使用accep_nested_attributes_for和polymorphico時不能批量分配受保護的屬性
我有一個forum_post模型和一個鏈接模型。我想將鏈接表單與forum_post表單嵌套,但不斷地得到一個無法批量分配受保護的屬性:鏈接。
ForumPost型號
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>
ForumPosts控制器
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
'ForumPostsController'的create方法在哪裏? – deefour 2012-07-25 17:22:01
你是否從'ForumPostsController#create','LinksController#create'或兩者獲得警告?我也沒有在'ForumPostsController#new'中看到'@ forum_post.links.build',這是故意的嗎? – HargrimmTheBleak 2012-07-25 17:31:48
錯誤消息僅在ForumPostsController#create上。我已經嘗試將@ forum_post.links.build添加到ForumPostsController#new,但仍然得到相同的錯誤 – otissv 2012-07-25 18:27:07