初學者的問題在這裏,任何幫助非常感謝。我有一個用戶表和一個產品表以及一個名爲products_users的連接表。我可以成功產品在命令行做這個鏈接到用戶:Rails - 如何將一個產品關聯到多個用戶?
u = User.where(:state => 'Oregon').first
u.products << Product.where(:search_location => 'Portland')
我的第一個問題是如何將我的波特蘭產品鏈接到有俄勒岡州,而不僅僅是一個用戶的所有用戶?如果我不添加.first,它不起作用。
但我的主要問題是如何讓應用程序做到這一點,而不是我在命令行中做到這一點?例如,我有一個包含10,000個用戶的表,其中1000個是:state =>'Oregon',那麼如何創建一個管理頁面,我可以在狀態字段中鍵入Oregon,然後在另一個字段中輸入Portland,條目鏈接在一起並添加到連接表中?
UPDATE
使用siddick的代碼中,我想出了這一點:
admin.rb
def link_product_to_user
products = Product.where(:search_location => params[:location])
User.where(:state => params[:state]).find_each do |user|
user.products << products
end
end
admin_controller.rb
def index
@link = link_product_to_user
end
管理員/ index.html的。 erb
<%= form_for(@link) do |f| %>
<div class="field">
<%= f.label :location %><br />
<%= f.text_field :location %>
</div>
<div class="field">
<%= f.label :state %><br />
<%= f.text_field :state %>
</div>
<div class="actions">
<%= f.submit %>
</div>
它提供了以下錯誤:
undefined local variable or method `link_product_to_user' for #<AdminController:0x007fd8e899bf10>
我應該如何界定方法,因此可以被發現的?並正在使用form_for(@link)正確的方式將值提交給方法?謝謝
你嘗試過什麼到目前爲止?有幾種方法可以做到這一點。 – simonmorley
另外,當你說'把俄勒岡州打入一個領域',你的意思是找到俄勒岡州的用戶,然後用州波特蘭州更新所有? – simonmorley
我不知道該怎麼做。我在初學者階段,如果我看到代碼,我會明白它是什麼,但是當面對一個空白頁我沒有線索從哪裏開始 – railsy