Search code examples
ruby-on-railsactiverecordsimple-form

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

One video can have only one category, but one category have several videos.

I let the users post video links and let them choose the best category for each video. I created some categories in admin and they can use only the ones I created.

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

Instead of having the categories, I just have the choice between "Yes" or "No" I can't use f.associations instead of f.input because I have an error saying I can't use associations with a "has_one" relationship.

What can I do ? I'm really stuck :(

Thank you


Solution

  • Since you are using has_many_through here for this simple association (as far as I see now), it is a bit over complicated. You could simply use normal 1 to many association without this third model (VideoCategory). But In your case:

    1. VideoContrller:

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

    1. video.rb:

    accepts_nested_attributes_for :video_category

    1. Database tables must contain:
    videos:
     video_category_id:integer
    categories:
     video_category_id:integer
    video_categories:
     video_id:integer
     category_id:integer
    
    1. Now you can set or create a VideoCategory record from the Video cotroller. Try in console:

    Video_category.create!

    Video.last.video_category = 1

    But I think for your case it would be easier to simply use one to many assoc, without the JoinedModel.

    Hope this will get you on tracks.