0
所以我有一個簡單的post模型has_many標籤:通過post_tags。這允許多對多的關係。不過,我一直無法獲得form_for和fields_for的工作。我真的被卡住了,因爲我無法通過has_many:through關係在form_for helper上找到任何文檔。我觀察了軌道投影,閱讀了以前的堆棧問題,甚至在Rails 3 Way中進行了研究。任何人,這是我得到的。form_for with has_many:通過
class Post < ActiveRecord::Base
belongs_to :blog
has_many :post_tags, :dependent => :destroy
has_many :tag, :through => :post_tags, :dependent => :destroy
has_many :post_categories, :dependent => :destroy
has_many :category, :through => :post_categories, :dependent => :destroy
attr_accessible(:title, ...)
accepts_nested_attributes_for :tag, :allow_destroy => true
end
和
class PostTag < ActiveRecord::Base
belongs_to :tag
belongs_to :post
end
和
class Tag < ActiveRecord::Base
has_many :post_tags
has_many :post, :through => :post_tags
end
和我的控制器代碼是
def new
@title = "Create a New Post"
@user = User.find(params[:user_id])
@blog = @user.blog
@post = @blog.post.new
@post.ptype = params[:type]
3.times { @post.tag.build}
end
def create
@user = User.find(params[:user_id])
@blog = @user.blog
@post = @blog.post.new(params[:post])
if @post.save
...
end
end
和形式是
<%= form_for([@user,@blog,@post],:url => user_blogs_posts_path, :html => {:multipart=>true}) do |p| %>
<%= render 'shared/error_messages', :object => p.object %>
...
<%= p.fields_for :tag do |t|%>
<%=t.label :tag %>
<%=t.text_field :tag %>
<% end %>
<%=p.submit%>
<% end %>
,誤差
Can't mass-assign protected attributes: tag_attributes
哇真的...我可以發誓,左,右,我已經試過了。但給它一個鏡頭和繁榮,它的工作。有趣的後續問題。如果可以使用現有記錄,我該如何告訴它...'如果Tag.find_by_name(params [:tag]'? – AdamCooper86 2012-07-21 18:38:26