这是我在rails中的应用程序的一部分: 如何从复选框中获取帖子控制器中的值? 我想从复选框中获取ID数组。 帖子已创建,但我无法访问从复选框中获取的ID数组。
class Categoryofpost < ActiveRecord::Base
belongs_to :post
belongs_to :category
end
............................
In views/posts/new.html.erb
<%= form_for @post do |p| %>
<%= p.label :title %>
<%= p.text_field :title %>
<br>
<%= p.label :body %>
<%= p.text_area :body %>
<br>
<p>Related to : </p>
<br>
<%= p.collection_check_boxes :category_ids, Category.all, :id, :name %>
<br>
<%= p.submit "Create" %>
<% end %>
&#13;
class Category < ActiveRecord::Base
belongs_to :user
validates :name, uniqueness: true
has_many :categoryofposts
has_many :related_posts, class_name: "Post", through: :categoryofposts , source: :post
end
....................
In the posts controler
def create
@post_params = post_params
#@post_params[:user_id] = 1 #session[:user_id]
@post = Post.new(@post_params)
if @post.save
# @cat = get_categories
# @cat.each do |c|
# Categoryofpost.create(post_id: @post.id, category_id: c)
# end
redirect_to @post, notice: "The post has been posted successfully."
else
render action: :new, alert: "The post has not been posted."
end
end
protected
def post_params
params.require(:post).permit(:title, :body, categoy_ids: [])
end
def get_categories
params.require(:post).permit(categoy_ids: [])
end
&#13;
class Post < ActiveRecord::Base
belongs_to :user, dependent: :destroy
has_many :categoryofposts
has_many :categories, through: :categoryofposts
end
&#13;
答案 0 :(得分:0)
你的post_params
方法中有一个拼写错误。它应该是
def post_params
params.require(:post).permit(:title, :body, category_ids: [])
end
注意 category_ids
。