Beginner question here, any help much appreciated. I have a table of users and a table of products and a join table called products_users. I can successfully link a product to a user in the command line by doing this:
u = User.where(:state => 'Oregon').first
u.products << Product.where(:search_location => 'Portland')
My first question is how would I link the Portland product to ALL users that have the state of Oregon and not just one user? If I don’t add the .first it doesn’t work.
But my main question is how to get the app to do this instead of me doing it in the command line? For instance, I have a table that contains 10,000 users and 1000 of them are :state => ‘Oregon’ so how do I create an admin page where I can type Oregon into the state field and then type Portland into another field and the appropriate entries are linked together and added into the join table?
UPDATE
Using siddick’s code I’ve come up with this:
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
admin/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>
which gives the following error:
undefined local variable or method `link_product_to_user' for #<AdminController:0x007fd8e899bf10>
How should I define the method so it can be found? And is using form_for(@link) the correct way to submit the values to the method? thanks
You can use
find_eachto process record one by one.Index View file can be: