2012-12-16 29 views
0

初學者的問題在這裏,任何幫助非常感謝。我有一個用戶表和一個產品表以及一個名爲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)正確的方式將值提交給方法?謝謝

+0

你嘗試過什麼到目前爲止?有幾種方法可以做到這一點。 – simonmorley

+0

另外,當你說'把俄勒岡州打入一個領域',你的意思是找到俄勒岡州的用戶,然後用州波特蘭州更新所有? – simonmorley

+0

我不知道該怎麼做。我在初學者階段,如果我看到代碼,我會明白它是什麼,但是當面對一個空白頁我沒有線索從哪裏開始 – railsy

回答

1

您可以使用find_each一個接一個地處理記錄。

def your_action 
    products = Product.where(:search_location => params[:location]) 
    User.where(:state => params[:state]).find_each do |user| 
    user.products << products 
    end if products.exists? 
    ... Your code ... 
end 

索引視圖文件可以是:

<%= form_tag(:action => "link_product_to_user") do %> 
    <div class="field"> 
    <%= label_tag :location %><br /> 
    <%= text_field_tag :location, params[:location] %> 
    </div> 
    <div class="field"> 
    <%= label_tag :state %><br /> 
    <%= text_field_tag :state, params[:state] %> 
    </div> 
    <div class="actions"> 
    <%= submit_tag %> 
    </div> 
<% end %> 
+0

嘿,看起來像我在找什麼,我必須現在運行,但稍後會嘗試它,並讓你知道,謝謝 – railsy

+0

嘿siddick,看到更新 – railsy

+0

你是一個明星siddick,它開箱即用,非常感謝您的幫助 – railsy

相關問題