dimanche 19 mars 2017

Adding Categories In Rails 3

I am building an uploader for videos and giving the videos a category through categorizations. Every time I try to upload a video I receive an error saying

NameError in VideosController#create

uninitialized constant Video::Categorization

I want to able to add one category to each video. But no regardless of how I write the association I get the same error.

model

 class Video < ActiveRecord::Base

  attr_accessible :source, :title, :url, :description,
                :category, :category_id, :category_list

 belongs_to :user

 has_many :category, through: :categorizations
 has_many :categorizations
 validates :category, presence: true

 has_attached_file :source

  def source_remote_url=(url_value)
   self.source = URI.parse(url_value) unless url_value.blank?
   super
  end

  def self.categorized_with(name)
    Category.find_by_name!(name).videos
  end

  def category_list
    ["Action",  "Anime",
      "Arts and Culture",  "Beauty",  "Business", "Comedy", 
      "Documentary", "Drama", 
      "Food",  "Gaming",  "Health and Fitness",  "Horror"]
  end 

  def category_list=(names)
    self.category = names.split(",").map do |n|
     Category.where(name: n.strip).first_or_create!
    end
  end

end

Video Controller

class VideosController < ApplicationController
  before_filter :authenticate_user!
  before_filter :set_video, only: [:show, :edit, :update, :destroy]

  respond_to :html

 def index
   @videos = Video.all
 end

 def show
  respond_with(@video)
 end

 def new
   @video = Video.new
   respond_with(@video)
 end

 def edit
 end

 def create
   @video = Video.new(params[:video])
   @video.save
   respond_with(@video)
 end

def update
  @video.update_attributes(params[:video])
  respond_with(@video)
end

 def destroy
  @video.destroy
  respond_with(@video)
 end

 private
   def set_video
     @video = Video.find(params[:id])
   end
end

Form

<%= form_for(@video) do |f| %>
  <% if @video.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@video.errors.count, "error") %> prohibited this video from being saved:</h2>

      <ul>
      <% @video.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>

  <div class="field">
    <%= f.label :source %><br />
      <%= f.file_field :source %>
  </div>

    <div class="field">
      <%= f.label "Category", class: 'control-label' %>
      <%#= f.select :category, Category.all, :prompt => 'Select One' %>
    <%= f.select :category_list, video_category, :prompt => "Select a category..." %>

    </div>

  <div class="field">
    <%= f.label :description %><br />
   <%= f.text_area :description, rows: 4, placeholder: "Description" %>

</div>
<div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Aucun commentaire:

Enregistrer un commentaire