Rails 3: Multiple Select with has_many through associations

后端 未结 5 2110
温柔的废话
温柔的废话 2020-11-27 11:24

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

I have next models: Post, Category and PostCategory.

class          


        
5条回答
  •  被撕碎了的回忆
    2020-11-27 11:56

    Final solution to organize categories in your posts, I hope it will be useful.

    To use multiple we need select_tag:

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

    Or f.select (many thanks to Tigraine and Brent!), it's more elegant way:

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

    In create action of our controller we need:

    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
    

提交回复
热议问题