新手问题 我有一个多对多关联的中间表,如何将数据保存在中间表中?

miserytan · 2017年05月24日 · 最后由 miserytan 回复于 2017年05月26日 · 5262 次阅读

假设我有三个表,表一为 projects,表二为 polls,中间表为 projects_polls,我想通过 创建 project 时选择数组 poll,并将数据更新到中间表中 表一和表二是多对多的关联,has_and_belongs_to_many,我需要怎么做?求大神指点

class Project < ActiveRecord::Base
  has_and_belongs_to_many  :polls
end
class Poll < ActiveRecord::Base
  has_and_belongs_to_many  :projects
end
class ProjectsPolls < ActiveRecord::Base
  unloadable
  belongs_to :project
  belongs_to :poll
end

project 表

create_table :projects do |t|
  t.string :name
  t.references :poll, index: true
  t.timestamps null: false
end

poll 表

create_table :polls do |t|
   t.string :name
   t.timestamps null: false
 end

中间表

create_table :projects_polls do |t|
  t.references :project, index: true
  t.references :poll, index: true
  t.timestamps null: false
end
project = Project.new(project_attrs)
project.polls.build(poll_attrs)
project.save

@wootaw 谢谢,完美解决问题

miserytan 关闭了讨论。 05月24日 13:12
miserytan 重新开启了讨论。 05月24日 14:23

@wootaw 还有个问题想问下您,如果我想在 project 选 poll 的时候,通过 checkbox,选择进来呢,如下 projects/form.html.erb:

<fieldset class="box tabular" id="projects_polls">
        <% @polls.each do |poll| %>
            <label class="floating">
            <% debugger %>

            <%= check_box_tag 'poll[poll_ids][]', poll.id, @project.polls.to_a.include?(poll), :id => nil %>
            <%= poll.name %>
            </label>
        <% end %>

        </fieldset>

这样进行选择的话,我应该怎么存储数据到中间表呢

project.update_attributes(poll_ids: params[:poll][:poll_ids])

@wootaw 感谢您的启发,我用了这样的方式 存储,谢谢

@polls = Poll.find(params[:poll][:poll_ids])
@project.polls<< @polls
miserytan 回复

如果仅仅是保存,你这么写多了一次不必要且效率低的查询。 其实我那句还可以写得更简单:

@project.update_attributes(params[:poll])
需要 登录 后方可回复, 如果你还没有账号请 注册新账号