2014-03-30 44 views
0

我希望每個用戶在註冊時上傳一個配置文件圖像。我有兩個模型,一個用戶模型和一個圖像模型。那麼,我應該如何使用新用戶更新用戶模型,以及使用一種形式爲該用戶提供新圖像的圖像模型?從一個表單創建兩個散列

用戶模型

class User < ActiveRecord::Base 
    has_one :profile_image, class_name: 'Image', foreign_key: 'user_id' 
end 

圖像模型

class Image < ActiveRecord::Base 
    # do I need to put something else here to make this relationship work? 
end 

用戶/新視圖

<%= form_for(@user) do |f| %> 
    <%= f.label :email %><br> 
    <%= f.text_field :email %> 

    <%= f.label :password %><br> 
    <%= f.password_field :password %> 

    # this needs to update a seperate params hash, but how? 
    <%= f.file_field :profile_image %> 

    <%= f.label :password_confirmation %><br> 
    <%= f.password_field :password_confirmation %> 



    <div class="actions"> 
     <%= f.submit %> 
    </div> 

<% end %> 

用戶#創建行動

def create 

    @user = User.new(user_params) 



    respond_to do |format| 
     if @user.save 

     # save their uploaded image 
     Image.create() # help needed here! 

     sign_in @user 
     format.html { redirect_to @user, notice: 'Welcome, ' + @user.user_name + '!' } 
     format.json { render action: 'show', status: :created, location: @user } 
     else 
     format.html { render action: 'new' } 
     format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 
    end 
end 

private 

# how do I create a method to require certain parameters for the Image? 

def user_params 
    params.require(:user).permit(:email, :password, :password_confirmation, :profile_image) 
end 

現在,我究竟做了在文件系統中創建自己的形象(通過rmagick),輕鬆一點,簡單地更新images表有關此圖像信息的硬盤位,是我掙扎的地方!

另外我知道嵌套窗體,但我認爲新圖像和新用戶都應在users#create操作中創建。這使得查看發生的事情變得更容易,而不是如果圖像是在其自己的image#create操作中創建的。我也在考慮將用戶創建和圖像創建置於交易塊中,但如果它們都發生在自己的行爲中,這是不可能的,所以我認爲答案是將表單分成兩個參數哈希值第一個散列,然後用第二個散列做其他事情。

+0

accept_nested_attributes_for有什麼問題? http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html –

+0

這似乎很有希望... – user3067865

回答

0

使用accepts_nested_attributes_for,開始時有點難以理解,但這正是您在這種情況下所需要的。事情是這樣的:

user.rb:

class User < ActiveRecord::Base 
    has_one :profile_image, class_name: 'Image', foreign_key: 'user_id' 
    accepts_nested_attributes_for :profile_image 
end 

的觀點:

<%= f.fields_for :profile_image do |f| %> 
    <%= file_field :file %> 
<% end %> 

控制器似乎是所有設置。

+0

這很奇怪..我有在用戶模型中建立的'has_one'(沒有很多)關係,我甚至可以在控制檯中運行'random_user.profile_image'(儘管它返回nil),但是當我使用'fields_for'方法時,無處可見。但是,如果我說'fields_for:profile_images'(複數),那麼它至少在視圖中出現。你知道這是爲什麼嗎? – user3067865

+0

嗯,這個問題解決了它(我需要調整'新'行動)http://stackoverflow.com/questions/12961168/ruby-on-rails-using-accepts-nested-attributes-for-does-not-生成-A-部分的叔?RQ = 1 – user3067865