[英]Using collection select in rails
我正在嘗試創建一個簡單的博客應用程序。 每個帖子都可以與標簽相關聯。 這是我的看法
_form.hmtl.erb
<%= form.collection_select(:tag_ids, @tags, :id, :name, {}, :multiple => true) %>
這是我的控制器
posts_controller.rb
def new
@post = @topic.posts.new
@tag = @post.tags.new
@tags = Tag.all
end
def create
@post = @topic.posts.new(post_params)
if @post.save
redirect_to topic_posts_path
else
render 'new'
end
end
def post_params
params.require(:post).permit(:title,:content,:post_image, tag_ids: [])
end
end
模型Post.rb
has_and_belongs_to_many :tags
創建新帖子“ Posts#create中的NoMethodError”,“ nil:NilClass的未定義方法'map'”時出現錯誤。 我找不到錯誤在哪里。
您應該有一個名為posts_tags.rb
表
class Post_Tag < ApplicationRecord
belongs_to :tag
belongs_to :post
end
因此,您已經有了一些要通過post和join表選擇的標簽,應該使用post_id
和tag_id
更新
在您的form_partial中進行更改:-
<%= select_tag "tag_ids", options_for_select(@tags,:id,:name),{}, multiple: true%> <br/><br/>
注意:-您不應該使用form.collection_select(:tag_ids...)
原因是@post
對象使用form_for
,而tag_ids
不是@post
對象的屬性。
因此,在提交表單時,您應該在params[:tag_ids]
獲得標簽ID的數組
def create
@post = @topic.posts.new(post_params)
if @post.save
#create join table for tags that are associated with post
@post.tags << Tag.find(params[:tag_ids])
redirect_to topic_posts_path
else
render 'new'
end
end
所以在這里你可以得到
@post.tags
=>將返回與該帖子相關的標簽的集合
如果使用這種情況,則必須在這兩個模型之間建立多對多關系。
has_and_belongs_to_many:標簽
然后在形式上你應該使用像
form.collection_select(:post,:tag_id,Tag.all,:id,:name_with_initial,提示:true)
在控制器中的create
操作中缺少@tags
變量-您已在new
聲明了它,但未在create
聲明它。 如果保存不成功並且操作嘗試重新呈現表單,則可能會導致視圖錯誤。
不確定是否就這樣,因為我不確定錯誤的確切位置。 但是正如您在評論之一中所說的那樣,當您使用Tag.all
而不是@tags
時,它可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.