Ruby on rails Rails 3:Multiple Select with具有多个直通关联

Ruby on rails Rails 3:Multiple Select with具有多个直通关联,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我想得到的可能性,选择几个类别为一个职位与多个选择 我有下一个模型:Post、Category和PostCategory class Post < ActiveRecord::Base has_many :post_categories has_many :categories, :through => :post_categories end class Category < ActiveRecord::Base has_many :post_categorie

我想得到的可能性,选择几个类别为一个职位与多个选择

我有下一个模型:Post、Category和PostCategory

class Post < ActiveRecord::Base
  has_many :post_categories
  has_many :categories, :through => :post_categories
end

class Category < ActiveRecord::Base
  has_many :post_categories
  has_many :posts, :through => :post_categories
end

class PostCategory < ActiveRecord::Base
  has_one    :post
  has_one    :category
  belongs_to :post      # foreign key - post_id
  belongs_to :category  # foreign key - category_id
end
在我的控制器中,我有类似@post=post.new的东西。 我已经创建了一些类别

我认为:

<%= form_for @post do |f| %>
    <%= f.text_field :title %>
    <%= f.select :categories, :multiple => true %>
    <%= f.submit %>
<% end %>

而且。。。我的分类在哪里?我只有多个选择选项。我认为我的表单有问题。

由于@post没有id,发件人可能不会显示类别,因为没有关联。你需要通过在@post上构建,比如

 @post = Post.new(:categories => Category.all)

您需要的是一个选项列表,用于选择:

<%= f.select :category_id, Category.all.collect {|x| [x.name, x.id]}, :multiple => true %>

最终的解决方案是在你的帖子中组织分类,希望对你有所帮助

要使用多个标签,我们需要选择标签:

<%= select_tag "categories", options_from_collection_for_select(Categories.all, 'id', 'name'), :multiple => true %>

Tigraine差点就拿到了,但您需要指定一个额外的空哈希:


真的%>

很抱歉让死人复活,但我发现了一个更简单的解决方案,它允许用户使用默认的控制器操作代码,并使用ActiveModel setter逻辑处理多个事件。是的,这完全是魔术

<%= f.select :category_ids, Category.all.collect {|x| [x.name, x.id]}, {}, :multiple => true %>

谢谢你的回复。对于build,我有一个未定义的方法“build”,用于。。。错误:那是因为没有这样的方法。它只在协会上可用。。他指的是Post.new:categories=>Category.all,但这意味着您的帖子已初始化为包含所有类别。谢谢!所有类别现在都可供选择。。。但不是多重选择:如果你有任何想法,我将不胜感激。我一开始忘记了答案中的多重=>真。。我大约在一个小时前更新了它..或者它可能是:html=>{:multiple=>true}我已经尝试了这两种变体,但都不起作用:在html中,我有:cat1 cat2耶,multiple与f.select不兼容。我已将其转换为true%>并且现在它在html中运行良好!:现在我有了真正的%>。在控制器的创建操作中,我有@post=post.newparams[:post]。在PostCategory中创建新记录需要什么?它与空哈希一起工作,谢谢!但在我的例子中:category\u id将是:categories。空哈希是用来做什么的?谢谢!我知道必须有一种简单而优雅的方法才能在Rails 3中工作:-@winfred我的设置几乎完全相同,只是我的帖子与类别有一种“一对一”的关系。has_many的name_ids方法是否有has_one等价物?在Formtastic中,它是f.input:categories这是集合\u select的目的:true}%>用于Rails 4中使用强参数的用户。要允许数组变量user:category\u id=>[]而不仅仅是:category\u id,请使用许可参数列表。
def create
   @post = Post.new(params[:post])

if @post.save

  params[:categories].each do |categories|
     categories = PostCategory.new(:category_id => categories, :post_id => @post.id)
     if categories.valid?
       categories.save
     else
       @errors += categories.errors
     end
  end
  redirect_to root_url, :notice => "Bingo!"
else
  render "new"
end
end
<%= f.select :category_ids, Category.all.collect {|x| [x.name, x.id]}, {}, :multiple => true %>
def post_params
  params.require(:post).permit(:title, :body, category_ids: [])
end