I have 3 Models: User
, Profile
and Photo
.
Profile < ApplicationRecord
belongs_to :user
has_many :photos, through: :user
Photo < ApplicationRecord
belongs to :user
User < ApplicationRecord
has_one :profile
has_many :photos
I'd like to build a form for @profile
that also displays checkboxes for all of its associated photos.
When a photo is checked, I'd like the that photo's #featured_status
to be turned to be TRUE
. (it has a default value of 1 in my database).
Photo class has these methods
class Photo < ApplicationRecord
belongs_to :user
has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
validates :image, :title, :description, presence: true
FEATURED_STATUS = { not_featured: 0, featured: 1 }
def featured?
self.featured_status == FEATURED_STATUS[:featured]
end
def not_featured?
self.featured_status == FEATURED_STATUS[:not_featured]
end
def myPhoto
ActionController::Base.helpers.image_tag("#{image.url(:thumb)}")
end
end
How can I build this form?
I've tried different variations of using fields_for
, collection_check_boxes, check_boxes and I can't seem to capture the information correctly.
At the moment this is my form.
<%= simple_form_for @profile do |f| %>
<%= f.input :bio, input_html: { class: 'form-control'} %>
<section class="main">
<label>Featured Profile Photos</label>
<% @profile.photos.each do |photo| %>
<%= form_for ([@profile, photo]) do |f| %>
<%= f.check_box :featured_status, :checked => (true if photo.featured?) %>
<%= f.submit %>
<% end %>
<label><%= photo.myPhoto %></label>
<% end %>
</section>
<%= f.button :submit %>
When the form renders, there are multiple "update" buttons - one for each photo. I'm also not able to submit the @profile.bio changes at the same time as updating a photo's featured_status.
Ideally, I'd like to have each of those photo update buttons to be hidden and just have one submit button that updates the Profile bio:text and renders the @profile.
At the same time, I'd like the photo.featured_status to be turned to true/false as soon as the checkbox is marked. (Maybe using Javascript?)
Any suggestions are really appreciated.