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

我有下一个模型: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的东西.刚出现的

我认为:

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

和我的分类在哪里?我在 Select 选项中只有"多个".我觉得我的表格有问题.

推荐答案

很抱歉让死人复活,但我找到了一个更简单的解决方案,可以使用默认的控制器操作代码,并使用ActiveModel setter逻辑来实现一个has_many.是的,这完全是魔法.

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

具体来说,使用:category_id(或:your_collection_id)参数名将自动告诉Rails调用

哦,加入,自动管理模型has_many :something, through: :something_else.太棒了.

因此,在OP中,只需将字段/参数名称改为:category_ids,而不是:categories.

这也将自动使模型的选定类别填充在编辑表单上高亮显示的 Select 字段中.

参考资料:

我在那里找到这个.

此外,the warning from the form helpers guide还解释了不使用正确的表单字段/参数名称时的这种"类型不匹配".

通过使用合适的字段名和参数来编辑精简/精简表单.

note for rails 4 and strong parameters:

def post_params
  params.require(:post).permit(:title, :body, category_ids: [])
end

Ruby-on-rails相关问答推荐

我如何在不在 gemfile 中的 rake 任务中要求 gem?

如何保持 en.yml DRY?

如何创建一个融合了另外两个记录的 FactoryBot 工厂?

如何启动 rails 控制台并专门使用测试数据库?

未初始化的常量 ActionDispatch::Session::EncryptedCookieStore (NameError)

ruby on rails 和 javascript 之间的时间转换反之亦然?

FactoryGirl + Faker - 为数据库种子数据中的每个对象生成相同的数据

Rails ActiveRecord 查询日期范围

设计和强大的参数

Rails - 获取没有 GET 参数的当前 url

Rails data-disable-with re-enable 按钮

如何获取包含表的列名的数组

设计自定义路由和登录页面

错误未初始化的常量 AWS (NameError)

link_to 将参数与 url 一起发送并在目标页面上抓取它们

ActiveRecord 查找现有表索引

设计:在注册期间禁用密码确认

Ruby on Rails:如何为 postgresql 编辑 database.yml?

从模型中获取验证

ActionMailer 在开发 Rails 4 中不发送邮件