2014-11-25 25 views
0

我目前使用Spotify的API來收集藝術家圖像,並且正如預期的那樣工作。在Rails中提供一個基於布爾值的回退圖像URL

require 'rspotify' 

class Artist < ActiveRecord::Base 
    attr_accessor: :image 

    before_save :get_image 

    def get_image 
     artist = RSpotify::Artist.search(self.name).first 
     if artist.nil? 
      self.image = '[email protected]' 
     else  
      self.image = artist.images.first 
      self.image = image['url'] 
     end 
    end 
end 

我擔心的是,有很多時候,其中一個藝術家共享相同的名稱一個是少爲人知引起有點查詢股價的。例如,如果我的網站上有一位名爲「John Doe」的藝術家,而Spotify也有一位具有相同名字的藝術家,但是是完全不同的人,則會顯示錯誤的人的圖像。

要解決這個問題,我想在我的編輯表單中添加一個複選框,詢問「正確的藝術家圖像?」。如果爲false,則從我的公共目錄中使用默認頭像。我現在唯一的問題是我的藝術家模型中的before_save回調無論如何都使用Spotify的圖像。有沒有一種方法可以在我的窗體的編輯視圖中設置一些東西,從某種意義上講,可以覆蓋此回調並根據我的複選框的值使用此回退URL?

<%= simple_form_for @artist do |f| %> 

    <div class="input"> 
     <%= f.input :name %> 
    </div> 

    <%= image_tag @artist.image %> 

    <%= label_tag 'Correct Artist Image?' %> 
    <%= check_box_tag 'Correct Artist Image?' %> 

    <%= f.submit %> 
<% end> 

顯示視圖

<% if correct_image %> 
    <%= image_tag @artist.image %> 
<% else %> 
    <%= image_tag '[email protected]' %> 
<% end %> 

回答

0

你仍然可以使用before_save回調你已經離開。如果圖像被標記爲正確,只需稍微重構一下,即可設置僅設置Spotify圖像的條件。

控制器/ artists_controller.rb

class ArtistsController < ApplicationController 
    def create 
    @artist = Artist.new(artist_params) 
    #... 
    @artist.save 
    end 

    private 
    def artist_params 
    params.require(:artist).permit(:is_correct_image) #... etc 
    end 

end 

型號/ artist.rb

class Artist < ActiveRecord::Base 

    attr_accessable :is_correct_image 

    before_save :assign_image 
    def assign_image 
    if @is_correct_image == '0' 
     set_spotify_image 
    else 
     set_default_image 
    end 
    end 

    private 
    def set_default_image 
    self.image = '[email protected]' 
    end 

    def set_spotify_image 
    artist = RSpotify::Artist.search(self.name).first 
    if artist.nil? 
     set_default_image 
    else 
     image = artist.images.first 
     self.image = image['url'] 
    end 
    end 
end 

view.html:這可以通過添加一個非持久性屬性Artist表單會用做.erb

... 
<%= f.check_box :is_correct_image %> 
+0

我唯一的問題乍看之下就在'assign_image'方法的第一行。 「@ is_correct_image」應該是一個實例變量嗎?我發現它引用了複選框的值,但我只是想了解它是如何實現的。它跳過我的原因之一是因爲我很習慣表示模型與屬性實例的變量。 – 2014-11-25 03:26:33

+0

是的,它的意思是一個實例變量而不是一個ActiveRecord屬性,因爲該值實際上並未保存到數據庫中。 'attr_accessor'允許'@ is_correct_image'到'Artist.new()'中的集合(以及AR屬性),這是'params'哈希設置'@ is_correct_image'的可能方式。 – Pete 2014-11-25 05:43:36

+0

有沒有辦法讓複選框在提交編輯表單後保持選中/取消選中狀態?這似乎是唯一不起作用的 – 2014-11-25 14:28:05

相關問題