2015-01-31 38 views
0

林想看看是否有更好的方式,通過documents遍歷每個skill贏得我的應用程序是我目前的實現是造成我用ajax訪問值的Rails

我的模型

時發出
class Skill < ActiveRecord::Base 
    has_many :documents 
end 

class Document < ActiveRecord::Base 
    belongs_to :skill 
    belongs_to :user 
end 

class User < ActiveRecord::Base 
    has_many :documents 
end 

在我看來public/index我顯示所有我Skills和每個用戶已連接到一個特定Skill

documents

查看

<% @skills.group_by(&:year_group_name).each do |key, value| %> 
    <h3><%= key %></h3> 
    <% value.group_by(&:aspect_name).each do |key_one, value_one| %> 
     <h4><%= key_one %></h4> 
     <% value_one.each do |s| %> 
      <% document = @documents.select { |d| d.skill_id == s.id } %> 
      <li><%= s.skill_description %> 
      <%= render partial: 'shared/documents/document_form', locals: { document: document } %> 
      </li> 
      <% end %> 
     <% end %> 
    <% end %> 

document_form

<% if document %> 
    <% document.each do |doc| %> 
    <%= doc %><!-- renders image if exists for user --> 
    <% end %>    
    <%= render template: '/documents/new' %> 
<% else %> 
    <%= render template: '/documents/new' %> 
<% end %> 

當我創建它是通過AJAX做,叫我create.js.erb

create.js.erb文檔

$('.doc_upload').html("<%= j render(partial: 'shared/documents/document_form', locals: { document: @documents }) %>") 

CRE在文件控制器吃行動

def create 
@document = current_user.documents.new(document_params) 
respond_to do |format| 
    if @document.save 
    format.html { redirect_to root_path, notice: success_save_msg } 
    format.js 
    else 
    format.html 
    format.js { render action: 'create.js.erb' } 
    end 
end 

當我渲染時我的問題create.js.erb(所以當驗證例如失敗)

你可以看到,我路過當地@documents,當其我打電話document_form正在迭代所有用戶文檔,而不僅僅是針對特定技能的文檔。

希望這是有道理的,我會很感激,如果任何人都可以給我任何指針

感謝

+0

對不起,但你能改說你的問題嗎?看來你在1線程下有太多問題,我對你的「真正」問題有點混淆。 – Finks 2015-02-01 01:07:49

+0

@Finks我已經重組了我的問題,希望現在有更多意義,謝謝 – Richlewis 2015-02-01 09:36:04

+0

也許我不能正確理解你的代碼,但是我沒有找到你在#create動作中定義\ @documents變量的位置。只有\ @文件。也許有任何提取所有用戶文檔的before_action? – hedgesky 2015-02-01 11:44:01

回答

0

你的問題,是因爲你試圖使用部分shared/documents/document_form。該部分期望document變量是一個數組而不是單個對象。我們可以在您的視圖中看到,您已經用文檔列表初始化了documentselect方法根據條件返回數組。

create動作,你已經初始化@document作爲一個Document對象,因此當您在局部,局部視圖中使用@document作爲你的價值爲document不會使你預期的結果。

要麼創建另一個可以處理您的預期視圖的部分,要麼重構您當前的局部以處理document變量的不同數據類型。

編輯: 所以基本上,在document_form部分,你在本地變量調用each方法document吧?當您通過ajax調用partial時,您無法通過current_user.documents.new(document_params)調用each這是document變量的值。

+0

謝謝你的回答,你能舉一個我怎麼處理這個請求的例子,不太清楚你的意思 – Richlewis 2015-02-02 19:15:02

+0

或更好,但你能看看http://stackoverflow.com/questions/28265610/cant- submit-form-after-validation-fails-rails,因爲我已經做了一些重構 – Richlewis 2015-02-02 19:26:57

+0

我已經提供了其他信息,希望這次可以得到它。 – Finks 2015-02-02 20:44:43