gpt4 book ai didi

ruby-on-rails-4 - Rails 与表单 collection_select 的多态关联,无需嵌套

转载 作者:行者123 更新时间:2023-12-04 07:00:19 25 4
gpt4 key购买 nike

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

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

最佳答案

从 Rails 4.2 开始,这可以通过 rails/globalid 处理.这个较新的选项被 Rails 的 ActiveJob 使用。它使解析和查找设置起来非常简单。
首先,检查您的 Gemfile.lockglobalid .对于 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 的东西......
文章 Controller :
# 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博文很有帮助。

关于ruby-on-rails-4 - Rails 与表单 collection_select 的多态关联,无需嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22190718/

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