2013-02-24 2 views
0

Я многое узнал из неоценимого ресурса stackoverflow. Я чрезвычайно благодарен за много замечательных вкладов. Да здравствует открытый источник и те, которые делают его реальным!RefineryCMS - Пользовательский движок изображения с использованием Dragonfly для множественного изменения размера при загрузке - MassAssign Ошибка при попытке выполнить учетную запись uid в базе данных

Для получения полной информации здесь я не смог найти правильный подход к моей проблеме здесь. Позволь мне объяснить.

Использование RefineryCMS v. 2.0.9 Я создал движок в приложении rails для презентации «Портфолио». A 'Портфолио' has_many ': экспонаты'. ': экспонат' принадлежит_to ': портфолио' согласно моделям ниже.

Предполагается, что атрибут модели: img_orginal - содержит uid для загрузки изображения Dragonfly. Это работает так, как и должно быть, загрузка изображения uid отправляется в базу данных и может быть вызвана в представление/портфолио/show.html.erb, как предполагалось. Предполагается, что сайт будет реагировать. Если он должен быть отзывчивым, ему нужен набор измененных больших пальцев, созданных из оригинала. Они должны быть созданы Dragonfly, когда: img_original загружается и выполняется через бэкэнд-форму. До сих пор я не смог добиться этого, используя Image_accessor Dragonfly в рамках модели экспонатов. Я получаю следующее исключение при попытке создания.

Может не массовые Присвоить защищенные атрибуты: img_original ActiveModel :: MassAssignmentSecurity :: Ошибка завод :: Портфели :: Администратор :: ExhibitsController # создать такие

Оба баз данных и правильно связаны через " : portfolio_id 'иностранного ключа в модели «экспонатов». Все атрибуты модели включены в белый список в соответствии с наилучшей практикой лучших рельсов.

Что мне не хватает? Я полагаю, что методы контроллера неправильны, я не могу понять, как они должны быть. Нужно ли менять контроллер двигателя, чтобы вызвать экземпляр класса Image Image или самого Стрекоза? Мне нужно изменить route.rb. Может ли кто-нибудь сообщить, как я буду определять методы создания и обновления контроллера. Это даже необходимо, учитывая, что они уже должны быть определены контроллером page_images основного приложения для НПЗ.

Я экспериментировал с методами, предложенными в документации Dragonfly с использованием image_accessor безрезультатно. Вот некоторые из подходов, взятых к настоящему времени.

ie.

image_accessor :img_original do 
after_assign :crop_thumb  #method defined below 
      #:resize_mobile, 
      #:resize_tablet, 
      #:resize_desktop 
# OR 
# copy_to(:img_thumb) do 
# |a| a.thumb('100x100') 
# end 
# OR different block syntax 
# copy_to(:img_thumb) do {|a| a.thumb('100x100')} 
end 

def crop_thumb 
    @exhibit.img_thumb = @exhibit.img_original.process(:resize_and_crop, 
                :width => 100, 
                :height=> 100, 
                :x => :x_focus, 
                :y => :y_focus).encode(:jpg, '-quality 60').apply 
end 

#def resize_mobile, 
    @exhibit.img_mobile = @exhibit.img_original.process(etc. 
#end 

#def resize_tablet, 
    etc. 

Я очень к этому не знаю, я продолжал изучать все, что могу, чтобы добиться этого. И все же я прихожу к этому и не могу взломать его. Я был бы признателен за любую помощь, которую вы могли бы предложить. Спасибо.

Примеры кода и информация об окружающей среде ниже.

Окружающая среда; Ubuntu 12,10 RubyMine IDE рубин 1.9.3 РВМ для обработки драгоценных камней Rails 3.2.9 SQLite DEV базы данных RefineryCMS (включая page_images и запросы плагинов) Dragonfly 0.9.14

Портфолио двигателя генерируется с этими миграциями

# This migration comes from refinery_portfolios (originally 1) 
class CreatePortfoliosPortfolios < ActiveRecord::Migration 

def up 
create_table :refinery_portfolios do |t| 
    t.string :title 
    t.integer :year 
    t.text :description 
    t.integer :publication_id 
    t.integer :commentary_id 
    t.integer :position 
    t.timestamps 
end 
end 

def down 
if defined?(::Refinery::UserPlugin) 
    ::Refinery::UserPlugin.destroy_all({:name => "refinerycms-portfolios"}) 
end 

if defined?(::Refinery::Page) 
    ::Refinery::Page.delete_all({:link_url => "/portfolios/portfolios"}) 
end 

drop_table :refinery_portfolios 
end 
end 

И

# This migration comes from refinery_portfolios (originally 2) 
class CreatePortfoliosExhibits < ActiveRecord::Migration 

def up 
create_table :refinery_portfolios_exhibits do |t| 
    t.string :title 
    t.integer :cat_num 
    t.integer :year 
    t.string :medium 
    t.integer :width 
    t.integer :height 
    t.integer :img_original_id 
    t.string :img_thumb 
    t.string :img_mobile 
    t.string :img_tablet 
    t.string :img_desktop 
    t.integer :x_focus 
    t.integer :y_focus 
    t.text :history 
    t.integer :portfolio_id 
    t.boolean :sold 
    t.integer :position 

    t.timestamps 
    end 

    end 

def down 
if defined?(::Refinery::UserPlugin) 
    ::Refinery::UserPlugin.destroy_all({:name => "refinerycms-portfolios"}) 
end 

if defined?(::Refinery::Page) 
    ::Refinery::Page.delete_all({:link_url => "/portfolios/exhibits"}) 
end 

drop_table :refinery_portfolios_exhibits 

end 

end 

И таблица refinery_portfolios_exhibits заголовки столбцов изменен

Exhibits table column header changed via migration 
class FixColumnName < ActiveRecord::Migration 
    def change 
    rename_column :refinery_portfolios_exhibits, :img_original_id, :img_original_uid 
    rename_column :refinery_portfolios_exhibits, :img_thumb, :img_thumb_uid 
    rename_column :refinery_portfolios_exhibits, :img_mobile, :img_mobile_uid 
    rename_column :refinery_portfolios_exhibits, :img_tablet, :img_tablet_uid 
    rename_column :refinery_portfolios_exhibits, :img_desktop, :img_desktop_uid 
    end 
end 

Портфолио модели содержит портфель метаданных, называемый «portfolio.rb ' has_many экспонат s модуль НПЗ модуль Портфели класс Портфолио < НПЗ :: Основной :: BaseModel self.table_name = 'refinery_portfolios'

attr_accessible :title, 
        :year, 
        :description, 
        :publication_id, 
        :commentary_id, 
        :position 

    acts_as_indexed :fields => [:title] 

    validates :title, :presence => true, :uniqueness => true 

    belongs_to :publication, :class_name => '::Refinery::Resource' 
    belongs_to :commentary, :class_name => '::Refinery::Resource' 

    # destroy all exhibits when a portfolio is destroyed 
    has_many :exhibits, :dependent => :destroy 

end 
end 
end 

Экспонат модель содержит ссылку на изображение и связанные с ними метаданные, называемый 'exhibit.rb'; belongs_to портфель

require 'dragonfly/rails/images' 

module Refinery 
module Portfolios 
class Exhibit < Refinery::Core::BaseModel 

attr_accessible :title, 
        :cat_num, 
        :year, 
        :medium, 
        :width, 
        :height, 
        :img_original_uid, #image upload uid from refinery_images table 
        :img_thumb_uid,  #commit resize uid here 
        :img_mobile_uid,  #here 
        :img_tablet_uid,  #here 
        :img_desktop_uid, #and here 
        :x_focus, 
        :y_focus, 
        :history, 
        :portfolio_id, #foreign key, associates exhbit with portfolio 
        :sold, 
        :position 

    acts_as_indexed :fields => [:title, :medium, :year, :cat_num] 

    validates :title, :presence => true, :uniqueness => true 
    validates :year, :length => { :is => 4, 
           :message => "Four digit year format,(yyyy) eg. 2013"} 
    validates :img_original_uid, :presence => true, :uniqueness => true        
    validates :portfolio_id, :presence => true 
    validates_associated :portfolio 
    validates :x_focus, :presence => true 
    validates :y_focus, :presence => true 
    validates :sold, :inclusion => {:in => [true, false]} 

    belongs_to :img_original, :class_name => '::Refinery::Image' 
    belongs_to :portfolio, :class_name => 'Portfolio', :foreign_key => 'portfolio_id' 
    end 
    end 
    end 

регулятору админ/exhibit.rb '

module Refinery 
    module Portfolios 
    module Admin 
    class ExhibitsController < ::Refinery::AdminController 
     before_filter :find_all_portfolios 

     crudify :'refinery/portfolios/exhibit', :xhr_paging => true 

     protected 

     def find_all_portfolios 
     @portfolios = Refinery::Portfolios::Portfolio.all 
     end 

    end 
    end 
end 
end 

'exhibit.rb' контроллера

module Refinery 
module Portfolios 
    class ExhibitsController < ::ApplicationController 

    before_filter :find_all_exhibits 
    before_filter :find_page 

    def index 
    #@exhibits = Exhibit.all(:include => :portfolio) 

    # you can use meta fields from your model instead (e.g. browser_title) 
    # by swapping @page for @exhibit in the line below: 
    present(@exhibit) 
    end 

    def show 
    @exhibit = Exhibit.find(params[:id]) 

    # you can use meta fields from your model instead (e.g. browser_title) 
    # by swapping @page for @exhibit in the line below: 
    present(@exhibit) 
    end 


    protected 

    def find_all_exhibits 
    @exhibits = Exhibit.order('position ASC') 
    end 

    def find_page 
    @page = ::Refinery::Page.where(:link_url => "/exhibits").first 
    end 

    end 
    end 
end 

ответ

0

Я предполагаю, что вы на самом деле не заботиться об этом какой-либо больше, так как вы просили 10 месяцев назад, но в вашей модели вы попробовали изменить

attr_accessible :img_original_uid 

в

attr_accessible :img_original 

ошибка приходит на img_original поле, пока вы даете доступ к img_original_uid. Я новичок в стрекозе также ...

 Смежные вопросы

  • Нет связанных вопросов^_^