ããªã¢ã¼ãã£ãã¯ã®åãã親ãçæãã
ããã«ã¡ã¯ãåãã¦ãç®ã«ãããæ¹ãåãã¾ãã¦ã
@return_right34ã¨ç³ãã¾ããä¸å¿ç¤¾å¡ã§ãã
æè¿ãããã¾ã§ã¨ã¯æã£ã¦å¤ãã£ãå¯æããããã¶ã¤ã³ã®ã¾ã¨ããµã¤ããå¶ä½ãã¦ããç§ã§ããã
ã¨ããåé¡ã«ã¶ã¤ããã¾ããã®ã§ãè¨äºãæ¸ãã¦ã¿ã¾ããã
åé¡ã®è¦ªå
# app/models/article.rb class Article has_many :items end # app/models/item.rb class Item belongs_to :article belongs_to :itemable, polymorphic: true end # app/models/text.rb class Text has_one :item, as: :itemable end
ãããªæãã«ããªã¢ã¼ãã£ãã¯ã«ãªã£ã¦ãã親åæ§é ãã
以ä¸ã®ãããªæµãã§ä¸åã®ãã©ã¼ã åä½ã§ãã¼ã¿çæããããã¨èãã¾ããã
article -> items -> itemable(Text, ...etc)
â¦â¦ããï¼ãåãã親ã®ä½æã£ã¦ã»ã»ã»ï¼ããããããªã¢ã¼ãã£ãã¯ã ãã»ã»ã»ã
çµè«ããç³ãã¾ãã¨ã以ä¸ã®ãããªæãã§ã³ã¼ãã追å ããã°åãã親ï¼ããªã¢ã¼ãã£ãã¯ãçæã§ãã¾ãã
Articleã¢ãã«ã¯ããæ®éã«
# app/models/article.rb class Article has_many :items accepts_nested_attributes_for :items end
ç¹è¨ãããã¨ã¯ããã¾ããã
Itemã¢ãã«ããããªæãã«
# app/models/item.rb class Item accepts_nested_attributes_for :itemable def attributes=(attributes = {}) self.itamable_type = attributes[:itemable_type] super end def itemable_attributes=(attributes) self.itemable = itemable_type.constantize.create_with(attributes).find_or_initialize_by(id: attributes['id']) self.itemable.attributes = attributes.slice(*%w(content)) if itemable.id end end
é©ããã®ã¯ãaccepts_nested_attributes_forããåãã親ã®éæã§ãåããã¨ãã»ã»ã»ãããããåããªãã£ããä¸åã®formåä½ã§çµãããªããªã£ã¦ãã¾ãã®ã¯ãããªã®ã§ããã
ä¸ã®ã¡ã½ããäºã¤ã¯ãããæ®éã®è¦ªåé¢ä¿ãªãå¿
è¦ãªããããªã®ã§ãããããªã¢ã¼ãã£ãã¯ã®å ´åã¯å®ç¾©ãããã¦ãªããããªã®ã§ãèªåã§è¿½å ãã¾ãã
以ä¸ã®URLã大å¤åèã«ãªãã¾ãããæè¬ãã¦ãããããªãã§ãã
http://stackoverflow.com/questions/3969025/accepts-nested-attributes-for-with-belongs-to-polymorphic
ã³ã³ããã¼ã©ã¯ãããªæãã«
# app/controllers/articles_controller.rb class ArticlesController def create @article = Articles.new(article_params) @article.save end private def article_params params[:article].permit(:title, items_attributes: [:itemable_type, itemable_attributes: [:content] ], ) end end
å
¥ãåæ§é ãéãã¦ããã¾ãã
ã¢ãã«ã«"belongs_to :itemable, polymorphic: true"ã¨è¨è¿°ããéãã«ã
åãã親ãçæããå ´åã§ãã£ã¦ã{é¢é£ã¢ãã«å}_attributesã¨æ¸ãã°éãã¿ããã§ãã
ãã©ã¼ã ã¯ãããªæãã«
# app/views/articles/new.html.erb <%= simple_form_for @article do |f| %> <%= f.input :title %> <%= f.simple_fields_for :items do |item| %> <%= f.input :itemable_type, as: :hidden, input_html: { value: 'Text' } %> #ããå¤§äº <%= f.simple_fields_for :itemable, Text.new do |itemable| %> <%= itemable.input :content %> <% end %> <% end %> <% end %>
ããããªãsimple_form使ã£ã¦ããã¾ãã
ã³ã³ããã¼ã©ã§ã¯ããã£ã¨æµãã¾ããããããªã¢ã¼ãã£ãã¯ã®ã¿ã¤ããæ示ãã¦ãããã¨ãéè¦ã§ããã§ãªããã°ã親ã«ä½ã®ã¯ã©ã¹ã®ã¤ã³ã¹ã¿ã³ã¹ãçæããã®ãããããªããªã£ã¦ãã¾ãã¾ãã
ããã§ç¡äºãarticleããitems, itemsããitemable(Text, ...etc)ãçæã§ããããã«ãªãã¾ããï¼
åèã«ãªãæ¹ãããã£ãããã°ã¨æãã¾ãã
ããã§ã¯ãä¹±æ失礼ãã¾ããã