2016-07-21 3 views
0

양식을 선택하기위한 옵션으로 내 이미지를 표시 할 수없는 곳에 문제가 있습니다. 사진 앨범을 만들고 동시에 앨범에 추가 할 사진을 선택하고 싶습니다.Ruby on Rails는 이미지를 양식의 체크 박스로 표시합니다.

"collection_check_boxes"를 시도했지만 옵션으로 표시 할 기존 이미지를 가져올 수 없습니다. 그리고 아직 그것을 (저장)하려하지 않았습니다.

나는 내 연관 관계가 있습니다. 이미지에 Paperclip Gem을 사용하고 있습니다.

모델 :

class Album < ActiveRecord::Base 
    belongs_to :user 
    has_many :photos 
end 

class Photo < ActiveRecord::Base 
    belongs_to :owner, class_name: 'User' 
    belongs_to :album 
    has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" 
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/ 
end 

컨트롤러 :

class AlbumsController < ApplicationController 
    before_action :authenticate_user!, only: [:create, :new] 

    def index 
    @albums = current_user.albums 
    end 

    def new 
    @photos = current_user.photos.all 
    @album = Album.new 
    end 

    def create 
    @album = albums.new(album_params) 
    if @album.save 
     redirect_to user_album_path(@album) 
    else 
     redirect_to root_path 
    end 
    end 

    def show 
    @album = Album.find(params[:id]) 
    end 

    def add_photo 
    end 

    private 
    def album_params 
     params.require(:album).permit(:name) 
    end 
end 

조회수 :

<%= form_for @album, url: user_albums_path do |f| %> 
    <form> 
     <div class="field"> 
     <%= f.label :Name %><br /> 
     <%= f.text_field :name %> 
     </div> 

     ####################Tried this but didn't work because the image isn't a text_method 
     <div> 
     <%= collection_check_boxes(:albums, :photo_ids, current_user.photos.all, :id, image_went_here) %> 
     </div> 
     #################### 
     <div class="actions"> 
     <%= f.submit "Create" %> 
     </div> 
    </form> 

    <% end %> 

답변

0
collection_check_boxes(:albums, :photo_ids, 
         current_user.photos.all, :id, :id) do |b| 
    b.label(class: "check_box") { 
     b.check_box(class: "check_box") + image_tag(object.image.url) 
    } 
end 

여기서 objectPhoto을 나타내는 블록에 current_user.photos.all을 표시합니다. Photo 모델과 일치하도록 object.photo.url 참조를 변경해야 할 수 있습니다. documentation에서 블록 collection_check_boxes의 사례를 참조하십시오.

+0

답변 감사합니다. 나는 당신의 제안을 시도했지만 불행히도 여전히 이미지를 표시하는 데 문제가있었습니다. 그것은 내가 사용하는 객체가 정의되지 않았다는 것을 계속 말합니다. 나는 그것을 다른 방법으로 해결했다. –

0

그래서 나는 모델에서 text_method 인수를 채우기 위해 메소드를 생성하여이를 해결할 수있었습니다.

보기 :

<%= collection_check_boxes(:albums, :photo_ids, @photos, :id, :myPhoto) %> 

모델 :

def myPhoto 
    ActionController::Base.helpers.image_tag("#{image.url(:thumb)}") 
end 

복제 된 방법은 나를 collection_check_boxes에 IMAGE_TAG를 삽입 할 수 모델.