2012-06-07 67 views
0

我想要做的是能夠添加註釋並將它們與Rails中的客戶端相關聯。Rails Association將form_for放在一個塊中

我的客戶端模式是這樣的:

class Client < ActiveRecord::Base 
    attr_accessible :company_name, :contact_name, :email_address, :phone_number, 
           :street_address, :city, :state, :zip 

    has_many :notes, dependent: :destroy 

end 

而且我的筆記模式是這樣的:

class Note < ActiveRecord::Base 
    attr_accessible :content 
    belongs_to :client 
    default_scope order: 'notes.created_at DESC' 

    validates :client_id, presence: true 
end 

我的我的客戶的index.html.erb看起來是這樣的:

<% @clients.each do |client| %> 
    . 
    . 
    . 
    <%= form_for(@notes) do |f| %> 
         <%= f.text_area :content, placeholder: "Compose new note..." %> 
         <%= f.submit "Add Note", class: "buttonPri addnote" %> 
        <% end %> 
<% end %> 

在我的客戶控制器我有:

def index 
    if signed_in? 
     @clients = Client.all 
    @note = client.notes.build 
    else 
     redirect_to signin_path 
     end 
end 

在我的筆記控制器:

def create 
    @note = client.notes.build(params[:note]) 
    if @note.save 
     flash[:success] = "Note Created" 
     redirect_to root_path 
     else 
     render 'static_pages/home' 
     end 
    end 

我得到undefined local variable or method client for #<ClientsController:0x007f835191ed18>錯誤,當我加載客戶端的索引頁。我認爲發生的事情是控制器無法看到塊變量client,我需要將其移出控制器並進入form_for。這是正確的方法,我該怎麼做?

我一直在尋找通過軌道API,發現這個:

<%= form_for([@document, @comment]) do |f| %> 
... 
<% end %> 
Where @document = Document.find(params[:id]) and @comment = Comment.new. 

這是我需要去的方向?

回答

2

問題在於您在控制器中指的是client,但這沒有定義。

根據您的例子:

def create 
    @note = client.notes.build(params[:note]) 
    if @note.save 
    flash[:success] = "Note Created" 
    redirect_to root_path 
    else 
    render 'static_pages/home' 
    end 
end 

client應該是哪裏來的?

before_filter :load_client 

def load_client 
    @client = Client.find_by_id!(params[:client_id]) 
end 

這可能是你有一個client方法定義爲返回nil,因爲它無法找到的東西:通常它是由父控制器類的before_filter調用,通常看起來像裝。在這種情況下,你應該跟蹤下來,看看問題是什麼。這是使用find!哪些引發異常而不是安靜地失敗通常是更好的方法。

當您在nil上看到與調用方法有關的錯誤時,這表示某個東西尚未正確加載,因此應該跟蹤該缺失的對象。

+0

我希望客戶端作爲塊變量出來@clients每個塊。但是,我不知道這是否可能。 load_client方法不起作用,因爲在單個頁面上有多個客戶端,我需要知道哪個客戶端與新筆記關聯。 –

+0

您視圖中定義的'client'變量與您的控制器無關,它們是兩個完全不同的上下文。事實上,該變量的範圍通常是*僅*在所討論的塊內。如果您同時爲多個客戶提交筆記,則需要以不同方式處理。標準REST調用一次只能針對一個對象。 – tadman

+0

對,我只想一次提交一個。這有點像twitter。我有一個推文列表(客戶端),但我可以回覆(向他們中的任何人添加註釋)。我如何確保使用正確的推文獲得正確的回覆? –