2012-11-07 46 views
1

我目前正在嘗試創建一個調查,該調查將使用存儲在表中的問題。我從軌道演員中讀到nested model form part 1,但由於問題沒有在調查中顯示,我沒有得到任何答案。Rails:使用數據庫表中的數據創建調查

我有三個表格,一個表格包含問題的文本,另一個表格保存誰進入調查的記錄以及第三個表格,用於保存用戶對問題的答案。

變量表: 名稱:VARCHAR ID:整數

報告表 員工姓名:VARCHAR 日期:日期 ID:整數

report_variable表 question_id REPORT_ID 答案

代碼,我修改了報告/新:

# GET /reports/new 
# GET /reports/new.json 
def new 
    @report = Report.new 
    #variable = @report.variable.build #dont know what to do here, gives an error with report_id 
    respond_to do |format| 
    format.html # new.html.erb 
    format.json { render json: @report } 
    end 
end 

修改報告/ _form.html.erb

<div > 
    <%= f.fields_for :variable do |builder| %> 
     <%= render variable_fields, :f => builder %> 
    <% end %> 
    </div> 

創建報告/ _variable_fields.html.erb

<p> 
     <%= f.label :name %> 
     <%= f.text_field :name, :class => 'text_field' %> 
    <p> 

模型report_variable

class ReportVariable < ActiveRecord::Base 
    attr_accessible :report_id, :value, :variable_id 
    has_and_belongs to many :reports 
    has_and_belongs to many :variables 
end 

模型報告

class Report < ActiveRecord::Base 
    attr_accessible :employeeName 
    has_many :report_variable 
    has_many :variable 

    accepts_nested_attributes_for :report_variable 
    accepts_nested_attributes_for :variable 
end 

很抱歉,如果這是一個簡單的問題,即時通訊漂亮的新軌道。

+0

歡迎來到Rails,究竟是什麼,你不確定/什麼是不工作? – Noz

+0

@CyleHunter謝謝,我更新了這個問題。問題在於調查中沒有顯示問題。 –

回答

2

歡迎來到Rails!

我認爲簡單的答案是字段沒有顯示,因爲沒有任何嵌套的記錄。你也許可以得到解決,通過取消註釋variable線,你就會明白:

def new 
    @report = Report.new 
    @report.variables.build #this line creates 1 new empty variable, unsaved. 
    respond_to do |format| 
    format.html # new.html.erb 
    format.json { render json: @report } 
    end 
end 

如果你想不止一個變量,調用是這樣的:

3.times { @report.variables.build } 

這樣的@report對象你放置在表單助手上會有三個變量。這應該讓你再次移動,更難的是要添加一個Ajax添加/刪除變量,但如果你知道事先有多少,你不必處理。

祝你好運!

+0

嗨,謝謝。問題是我在變量表中有一些示例數據,例如3行。我如何穩固這種關係?Thx –

+0

如果你有複雜的邏輯進行,你可能想在模型層中處理這個問題。在報告中創建一個類似於'load_variables'的方法,並將您的邏輯加載到變量中。只要你在頁面上加載了與報表相關的變量,就會正確地獲得嵌套表單。 – Andrew