Skip to content

Instantly share code, notes, and snippets.

@JoshCheek

JoshCheek/index.haml

Last active Feb 18, 2021
Embed
What would you like to do?
How to get Rails' radio buttons to work.
%ul
- @omghis.each do |omghi|
%li
= omghi.wtf
= image_tag omghi.media.variant(resize: "339x243") if omghi.media.present?
:css
.omgsection { border: 1px solid black; }
= form_for @omghi, controller: :omghi, method: :create do |f|
.omgsection
= f.label :wtf
= f.text_field :wtf
.omgsection
- @images.each do |image|
%div
= f.radio_button :media_filename, image
= f.label :media_filename, value: image do
= image_tag image
.omgsection
= f.submit 'Create!'
class AddOmghis < ActiveRecord::Migration[6.0]
def change
create_table :omghis do |t|
t.string :wtf
end
end
end
class Omghi < ApplicationRecord
has_one_attached :media
validates :wtf, presence: true
def media_filename
return '' if media.blank?
media.filename.to_s
end
end
class OmghiController < ApplicationController
before_action do
@omghis = Omghi.all
@images = ['avatar_01.png', 'avatar_02.png',]
end
def index
@omghi = Omghi.new
end
def create
omghi_params = params.require(:omghi).permit(:wtf, :media_filename)
basename = File.basename omghi_params.delete(:media_filename).to_s
path = Rails.public_path/'images'/basename
@omghi = Omghi.new(omghi_params)
@omghi.media.attach io: path.open, filename: path.basename if path.exist?
if @omghi.save
redirect_to omghis_path
else
render :index
end
end
end
+ get '/omghi', to: 'omghi#index', as: :omghis
+ post '/omghi', to: 'omghi#create'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment