2014-03-05 34 views
2

我在我的應用程序有以下型號導軌和形式collection_select態關聯不築巢

class User < ActiveRecord::Base 
has_many :articles 
has_many :tour_companies 
has_many :accomodations 
end 

class Articles < ActiveRecord::Base 
belongs_to :user 
belongs_to :bloggable, :polymorphic => true 
end 

class TourCompany < ActiveRecord::Base 
belongs_to :user 
has_many :articles, :as => :bloggable 
end 

class Accommodation < ActiveRecord::Base 
belongs_to :user 
has_many :articles, :as => :bloggable 
end 

現在我的問題是我想要登錄的用戶能夠寫一篇文章,並使用一種形式collection_select選擇他/她的哪家旅遊公司或住宿文章應該與之相關聯,我如何在rails 4中執行此操作?我如何從表單集合select中選擇bloggable類型和id?我不想嵌套的資源

回答

5

所以我終於做到了。以下是我做到了 的意見/文章/ _form.html.erb

<div class="row"> 
<% bloggable_collection = TourCompany.all.map{|x| [x.title, "TourCompany:#{x.id}"]} + 
          Accomodation.all.map{|x| [x.title, "Accomodation:#{x.id}]} 
%> 
<p>Select one of your listing this article is associated with</p> 
<%= f.select(:bloggable, bloggable_collection,:selected =>"#{f.object.bloggable_type}:# {f.object.bloggable_id}") %> 
</div> 

然後在文章控制器

#use regular expression to match the submitted values 
def create 
bloggable_params = params[:article][:bloggable].match(/^(?<type>\w+):(?<id>\d+)$/) 
params[:article].delete(:bloggable) 

@article = current_user.articles.build(article_params) 
@article.bloggable_id   = bloggable_params[:id] 
@article.bloggable_type  = bloggable_params[:type] 
if @article.save 
    redirect_to admin_root_url, :notice => "Successfully created article" 
else 
    render 'new', :alert => "There was an error" 
end 
end 

,它應該工作!