gpt4 book ai didi

ruby-on-rails - rails 3 : Multiple Select with has_many through associations

转载 作者:行者123 更新时间:2023-12-03 05:52:56 25 4
gpt4 key购买 nike

我希望能够通过多项选择为一篇帖子选择多个类别。

我有下一个模型: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

在我的 Controller 中,我有类似 @post = Post.new 的内容。我创建了一些类别。

我认为:

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

而且...我的类别在哪里?我的选择选项中只有“多个”。我认为我的表单有问题。

最佳答案

抱歉让死者复活,但我发现了一个更简单的解决方案,可以让人们使用默认 Controller 操作代码并使用 has_many 的 ActiveModel setter 逻辑。是的,这太神奇了。

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

具体来说,使用 :category_ids (或 :your_collection_ids)参数名称将自动告诉 Rails 调用@post.category_ids = params[:post][:category_ids] 相应地设置该帖子的类别,所有这些都无需修改默认 Controller /支架 #create 和 #update 代码。

哦,它可以与has_many :something, through: :something_else一起自动管理连接模型。太棒了。

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

这也会自动让模型的选定类别填充选择字段,并在编辑表单上突出显示。

引用文献:

From the has_many API docs我在哪里找到这个的。

还有the warning from the form helpers guide解释了未使用正确的表单字段/参数名称时出现的“类型不匹配”情况。

通过使用正确的表单字段/参数名称,您可以干燥新表单并编辑表单并保持 Controller 的精简,正如 Rails 方式所鼓励的那样。

rails 4 和强参数的注释:

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

关于ruby-on-rails - rails 3 : Multiple Select with has_many through associations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8826407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com