Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

Rails 3: Multiple Select with has_many through associations

I want to get possibility to select several Categories for one Post with multiple select.

I have next models: Post, Category and 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

In my controller I have something like @post = Post.new . I've created some categories.

And in view I have:

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

And... where is my categories? I have only "multiple" in select options. I think it's something wrong with my form.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sorry to resurrect the dead, but I found a much simpler solution that lets one use the default controller action code and use the ActiveModel setter logic for a has_many. Yes, it's totally magic.

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

Specifically, using the :category_ids (or :your_collection_ids) param name will automagically tell Rails to call @post.category_ids = params[:post][:category_ids] to set the categories for that post accordingly, all without modifying the default controller/scaffold #create and #update code.

Oh, and it works with has_many :something, through: :something_else automatically managing the join model. Freaking awesome.

So from the OP, just change the field/param name to :category_ids instead of :categories.

This will also automatically have the model's selected categories populate the select field as highlighted when on an edit form.

References:

From the has_many API docs where I found this.

Also the warning from the form helpers guide explains this "type mismatch" when not using the proper form-field/parameter name.

By using the proper form-field/param name, you can dry up new and edit forms and keep the controllers thin, as encouraged by the Rails way.

note for rails 4 and strong parameters:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...