Ruby on rails Rails-如何将一个产品与多个用户关联?
初学者问题在这里,任何帮助非常感谢。我有一个用户表、一个产品表和一个名为products\u users的连接表。通过执行以下操作,我可以在命令行中将产品成功链接到用户:Ruby on rails Rails-如何将一个产品与多个用户关联?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,初学者问题在这里,任何帮助非常感谢。我有一个用户表、一个产品表和一个名为products\u users的连接表。通过执行以下操作,我可以在命令行中将产品成功链接到用户: u = User.where(:state => 'Oregon').first u.products << Product.where(:search_location => 'Portland') admin/index.html.erb <%= form_for(@link) do |f|
u = User.where(:state => 'Oregon').first
u.products << Product.where(:search_location => 'Portland')
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>
这会产生以下错误:
undefined local variable or method `link_product_to_user' for #<AdminController:0x007fd8e899bf10>
未定义的局部变量或方法“将产品链接到用户”#
我应该如何定义方法才能找到它?使用(@link)的表单_是否是向方法提交值的正确方法?谢谢您可以使用
查找每个
逐个处理记录
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
def您的_操作
产品=产品。其中(:搜索\位置=>参数[:位置])
User.where(:state=>params[:state])。查找每个do |用户|
用户产品
到目前为止,您尝试过什么吗?有两种方法可以做到这一点。另外,当你说“将俄勒冈州键入一个字段”时,你的意思是找到俄勒冈州用户,然后用波特兰州更新所有内容吗?我不知道怎么做。我正处于初级阶段,如果我看到代码,我会理解它的功能,但当面对一个空白页面时,我不知道从哪里开始。我的意思是找到具有名为Oregon的状态字段(状态列在users表中)的用户,然后将他们链接到具有名为Portland的搜索位置字段的产品(search_location是products表中的一个字段)您需要搜索、更新或两者的帮助吗。Shey这看起来像我正在寻找的,我现在必须运行,但稍后会尝试,并让您知道,谢谢您是star siddick,它可以立即运行,非常感谢您的帮助
undefined local variable or method `link_product_to_user' for #<AdminController:0x007fd8e899bf10>
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 %>