【问题标题】:Rails 5 - Simple_form and has_one associationRails 5 - Simple_form 和 has_one 关联
【发布时间】:2017-03-26 02:07:38
【问题描述】:

模型/视频

class Video < ApplicationRecord
  has_one :category, through: :video_category
  has_one :video_category
end

型号/类别

class Category < ApplicationRecord
  has_many :video_categories
  has_many :videos, through: :video_categories
end

一个视频只能有一个类别,但一个类别可以有多个视频。

我让用户发布视频链接并让他们为每个视频选择最佳类别。我在管理员中创建了一些类别,它们只能使用我创建的类别。

观看次数/视频/新

<%= simple_form_for @new_video do |f| %>
   <%= f.input :title %>
   <%= f.input :description, as: :text %>
   <%= f.input :category,
               as: :select,
               label: "Category" %>
   <%= f.button :submit, "Submit", class:"btn btn-danger post-button-form" %>
<% end %>

没有类别,我只能在“是”或“否”之间进行选择 我不能使用 f.associations 而不是 f.input,因为我有一个错误说我不能使用具有“has_one”关系的关联。

我能做什么?我真的被困住了:(

谢谢

【问题讨论】:

    标签: ruby-on-rails activerecord simple-form


    【解决方案1】:

    由于您在这里使用has_many_through 进行这个简单的关联(据我现在所见),它有点过于复杂。您可以简单地使用普通的一对多关联,而无需第三个模型(VideoCategory)。但在你的情况下:

    1. 视频控制器:

    params.require(:video).permit(:name, :description, video_categories_attributes: [:id, :foo, :bar])

    1. video.rb:

    accepts_nested_attributes_for :video_category

    1. 数据库表必须包含:
    videos:
     video_category_id:integer
    categories:
     video_category_id:integer
    video_categories:
     video_id:integer
     category_id:integer
    
    1. 现在您可以从 Video 控制器设置或创建 VideoCategory 记录。在控制台中尝试:

    Video_category.create!

    Video.last.video_category = 1

    但我认为对于您的情况,简单地使用一对多 assoc 会更容易,而无需 JoinedModel。

    希望这能让你走上正轨。

    【讨论】:

    • 感谢您的回答。你是对的,一对多的关联对我来说要好得多。我修改了我的模型,现在一切正常。
    • 很好,很高兴它有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多