我的问题是不会创建一个嵌套在帖子中的标签。
我有Post,其中嵌有标签。喜欢这个
resources :posts do
resources :tags, :only => [:new, :create, :destroy]
end
在我的代码控制器中,我有这个
class TagsController < ApplicationController
before_filter :authenticate_user!
def new
@post = Post.find(params[:post_id])
@tag = Tag.new
end
def create
@post = Post.find(params[:post_id])
@tag = @post.tags.build(params[:tags])
if @tag.save
flash[:notice] = "Tag created"
redirect_to @tag.post
else
flash[:error] = "Could not add tag at this time"
redirect_to @tag.post
end
end
end
new.html.erb
<%= form_for [@post, @tag] do |f| %>
<% if @tag.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@tag.errors.count, "error") %> prohibited this tag from being saved:</h2>
<ul>
<% @tag.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.text_field :tagable_type, :placeholder => "Type" %>
</div>
<div class="field">
<%= f.text_field :tagable_id, :placeholder => "Id" %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
标记模型
class Tag < ActiveRecord::Base
attr_accessible :post_id, :user_id, :tagable_type, :tagable_id
validates :post_id, presence: true
belongs_to :tagable, :polymorphic => true
belongs_to :post
belongs_to :user
end
发布模型
class Post < ActiveRecord::Base
attr_accessible :body, :link, :thumbnail, :title, :user_id, :youtube, :youtube_id, :website_name, :image_field
default_scope order: 'posts.active DESC'
has_many :tags, :dependent => :destroy
has_many :comments, :as => :commentable, :dependent => :destroy
belongs_to :user
end
更新
现在我可以创建一个标签但是没有为某些reaseon创建tagable_type和tagable_id字段
Started POST "/posts/18/tags" for 127.0.0.1 at 2013-06-26 15:54:14 +0200
Processing by TagsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"gwpTs0Qqcrre4tH974RrfpaENGZKtSbkJx2U0H67AcM=", "tag"=>{"tagable_type"=>"Player", "tagable_id"=>"2"}, "commit"=>"Create Tag", "post_id"=>"18"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? ORDER BY posts.active DESC LIMIT 1 [["id", "18"]]
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "tags" ("created_at", "post_id", "tagable_id", "tagable_type", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?) [["created_at", Wed, 26 Jun 2013 13:54:14 UTC +00:00], ["post_id", 18], ["tagable_id", nil], ["tagable_type", nil], ["updated_at", Wed, 26 Jun 2013 13:54:14 UTC +00:00], ["user_id", 1]]
(6.9ms) commit transaction
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = 18 ORDER BY posts.active DESC LIMIT 1
Redirected to http://localhost:3000/posts/18
Completed 302 Found in 15ms (ActiveRecord: 7.9ms)
答案 0 :(得分:1)
create()
的{{1}}行动中存在拼写错误:
TagsController
用于创建代码的哈希值应为@tag = @post.tags.build(params[:tags])
,而不是params[:tag]
。