Rails 5 - Simple_form 和 has_one 关联

Rails 5 - Simple_form and has_one association

models/video

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

models/category

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

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

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

views/videos/new

<%= 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 %>

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

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

谢谢

由于您在这里使用 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. 现在您可以从视频控制器设置或创建 VideoCategory 记录。在控制台中尝试:

Video_category.create!

Video.last.video_category = 1

但我认为对于您的情况,在没有 JoinedModel 的情况下简单地使用一对多关联会更容易。

希望这能让你走上正轨。