Rails与表单collection_select的多态关联,没有嵌套

问题描述 投票:3回答:2

我的应用程序中有以下模型

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中做到这一点?如何从表单集选择中选择bloggable类型和id?我不想要嵌套资源

ruby-on-rails-4 polymorphic-associations
2个回答
5
投票

所以我设法最终做到了。这是我在views / articles / _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

它应该工作!


3
投票

从Rails 4.2开始,这可以通过rails/globalid来处理。这个更新的选项由Rails的ActiveJob使用。它使解析和查找设置非常简单。

首先,检查你的Gemfile.lock globalid。对于Rails 5,它包括在内。

神奇的一切都发生在模型中......

文章模型:

# Use :to_global_id to populate the form
def bloggable_gid
  bloggable&.to_global_id
end

# Set the :bloggable from a Global ID (handles the form submission)
def bloggable_gid=(gid)
  self.bloggable = GlobalID::Locator.locate gid
end

为了感受这一点,打开一个rails console。和gid = TourCompany.first.to_global_idGlobalID::Locator.locate gid一起玩。

现在剩下的代码是库存Rails的东西......

文章控制器:

# consider building the collection in the controller.
# For Rails 5, this would be a `before_action`.
def set_bloggables
  @bloggables = TourCompany.all + Accomodation.all
end

# permit :bloggable_gid if you're using strong parameters...
def article_params
  params.require(:article).permit(:bloggable_gid)
end

文章形式:

<%= f.collection_select(:bloggable_gid, @bloggables, :to_global_id, :to_s) %>

有关更多的演练,Simple Polymorphic Selects with Global IDs博客文章很有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.