0

ここでの初心者の質問、どんな助けでも大歓迎です。ユーザーのテーブルと製品のテーブル、products_users という結合テーブルがあります。これを行うことで、コマンドラインで製品をユーザーに正常にリンクできます。

u = User.where(:state => 'Oregon').first
u.products << Product.where(:search_location => 'Portland')

最初の質問は、1 人のユーザーだけでなく、オレゴン州のすべてのユーザーにポートランド製品をリンクするにはどうすればよいですか? .first を追加しないと機能しません。

しかし、私の主な質問は、コマンドラインで行うのではなく、アプリにこれを行わせる方法ですか? たとえば、10,000 人のユーザーを含むテーブルがあり、そのうちの 1000 人が :state => 'Oregon' である場合、州フィールドに Oregon と入力し、別のフィールドに Portland と入力して適切なエントリは一緒にリンクされ、結合テーブルに追加されますか?

アップデート

シディックのコードを使用して、これを思いつきました:

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) を使用して値をメソッドに送信する正しい方法はありますか? ありがとう

4

1 に答える 1

1

find_eachレコードを1つずつ処理するために使用できます。

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

Index View ファイルは次のようになります。

<%= 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 %>
于 2012-12-16T17:17:11.987 に答える