我想要做的是能夠添加註釋並將它們與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.
這是我需要去的方向?
我希望客戶端作爲塊變量出來@clients每個塊。但是,我不知道這是否可能。 load_client方法不起作用,因爲在單個頁面上有多個客戶端,我需要知道哪個客戶端與新筆記關聯。 –
您視圖中定義的'client'變量與您的控制器無關,它們是兩個完全不同的上下文。事實上,該變量的範圍通常是*僅*在所討論的塊內。如果您同時爲多個客戶提交筆記,則需要以不同方式處理。標準REST調用一次只能針對一個對象。 – tadman
對,我只想一次提交一個。這有點像twitter。我有一個推文列表(客戶端),但我可以回覆(向他們中的任何人添加註釋)。我如何確保使用正確的推文獲得正確的回覆? –