我希望每個用戶在註冊時上傳一個配置文件圖像。我有兩個模型,一個用戶模型和一個圖像模型。那麼,我應該如何使用新用戶更新用戶模型,以及使用一種形式爲該用戶提供新圖像的圖像模型?從一個表單創建兩個散列
用戶模型
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
操作中創建的。我也在考慮將用戶創建和圖像創建置於交易塊中,但如果它們都發生在自己的行爲中,這是不可能的,所以我認爲答案是將表單分成兩個參數哈希值第一個散列,然後用第二個散列做其他事情。
accept_nested_attributes_for有什麼問題? http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html –
這似乎很有希望... – user3067865