2012-07-08 51 views
0

我有一個模型,如下所示:Ruby on Rails如何在本例中訪問模​​型內​​部的模型變量?

# == Schema Information 
# 
# Table name: s3_files 
# 
# id      :integer   not null, primary key 
# owner     :string(255) 
# notes     :text 
# created_at    :datetime  not null 
# updated_at    :datetime  not null 
# last_accessed_by_user :string(255) 
# last_accessed_time_stamp :datetime 
# upload_file_name   :string(255) 
# upload_content_type  :string(255) 
# upload_file_size   :integer 
# upload_updated_at  :datetime 
# 

class S3File < ActiveRecord::Base 

    #PaperClip methods 
    attr_accessible :upload 
    attr_accessor :owner 

    Paperclip.interpolates :prefix do |attachment, style| 
    I WOULD LIKE TO ACCESS VARIABLE= owner HERE- HOW TO DO THAT? 

    end 

    has_attached_file( :upload, 
        :path => ":prefix/:basename.:extension", 
        :storage => :s3, 
        :s3_credentials => {:access_key_id => "ZXXX", 
             :secret_access_key => "XXX"}, 
        :bucket => "XXX" 
       ) 


    #Used to connect to users through the join table 
    has_many :user_resource_relationships 
    has_many :users, :through => :user_resource_relationships 

end 

進出口設置該變量在控制器中,像這樣:

# POST /s3_files 
    # POST /s3_files.json 
    def create 
    @s3_file = S3File.new(params[:s3_file]) 
    @s3_file.owner = current_user.email 

    respond_to do |format| 
     if @s3_file.save 
     format.html { redirect_to @s3_file, notice: 'S3 file was successfully created.' } 
     format.json { render json: @s3_file, status: :created, location: @s3_file } 
     else 
     format.html { render action: "new" } 
     format.json { render json: @s3_file.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

感謝,任何幫助,將不勝感激。

回答

1

只需使用所有者或self.owner得到的變量

+0

如果我使用self.owner,我得到這個: 「NoMethodError in S3_files#index。 Showing /Users/AM/Documents/RailsWS/app0521/app/views/s3_files/index.html。 erb哪裏行#22提出: 未定義的方法'所有者'的回形針::插值:模塊 – banditKing 2012-07-08 15:26:10

+0

如果我使用:所有者,它在回形針方法中使用文字詞「所有者」 – banditKing 2012-07-08 15:28:31

+1

對不起,我沒有閱讀您的問題第一次嘗試做類似attachment.instance.s3file.owner – chrisbulmer 2012-07-08 15:37:36

0

你甚至嘗試只是把owner,看看它的工作?

+0

是的,它沒有工作。看到我的評論@ chrisbulmer的文章 – banditKing 2012-07-08 15:29:01

0

此代碼:attr_accessor :owner在類的類生成getter和setter方法有效地給你一個實例方法。

因此,在您conrtroller,你必須叫@s3_file讀所有者的S3File實例只是使用[email protected]_file.owner並設置它只是去@s3_file.owner="asdf"

如果你想讀/寫的S3File的implementaiton裏面只是去val=self.ownerself.owner="asdf"self是可選的。