Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active February 18, 2021 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/7b33d126732f4aaad89a20c6c10c3beb to your computer and use it in GitHub Desktop.
Save JoshCheek/7b33d126732f4aaad89a20c6c10c3beb to your computer and use it in GitHub Desktop.
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