添加仅包含父模型ID的表的条目

时间:2015-07-07 14:53:41

标签: ruby-on-rails ruby-on-rails-4 activerecord associations nested-forms

我在应用中有两个模型:PersonDirector; person has_one director。一个人可以是很多东西(官员,承包商等和导演);如果他们是导演,我只想将他们的用户ID存储在导演表中,仅此而已。

因此,我设置的表只包含4列:

mysql> show columns in directors;
+------------+----------+------+-----+---------+----------------+
| Field      | Type     | Null | Key | Default | Extra          |
+------------+----------+------+-----+---------+----------------+
| id         | int(11)  | NO   | PRI | NULL    | auto_increment |
| person_id  | int(11)  | YES  | MUL | NULL    |                |
| created_at | datetime | YES  |     | NULL    |                |
| updated_at | datetime | YES  |     | NULL    |                |
+------------+----------+------+-----+---------+----------------+
4 rows in set (0.03 sec)

我希望表单上的每个人都有一个嵌套的单选按钮,如果设置为“是”则在​​director表中创建一个条目,如果设置为“No”则删除/不创建条目。看起来很简单,但我意识到我不知道该怎么做,因为单选按钮的显式值不会保存到数据库中。

有没有好办法解决这个问题?

2 个答案:

答案 0 :(得分:2)

您可以向attr_accessor模型添加Person,例如is_director。这是一个临时属性,不会存储在数据库中。然后根据is_director的值,您可以使用回调来设置逻辑,使用户成为自己的导演。

class Person < ...
  ...

  attr_accessor :is_director
  after_create  :make_director

private

  def make_director
    if self.is_director
      #your logic to make the user their own director
    else
      #some other logic
    end
  end
end

然后在表单中,您可以添加单选按钮:

<%= f.label :is_director %><br />
<%= f.label :is_director, "Yes", :value => "true"  %>
<%= f.radio_button :is_director, true, :checked => is_director?(@person)  %>
<%= f.label :is_director, "No", :value => "false" %>
<%= f.radio_button :is_director, false, :checked => !is_director?(@person) %>

然后你可以在persons_helper.rb中创建一个帮助器:

def is_director?(person)
  #whatever the logic is to check if a person is a director
end

您还需要将is_director添加到控制器中强参数的permit数组中。

答案 1 :(得分:0)

如果没有其他角色需要的任何其他属性,那么拥有一个包含导演,管理员,承包商等记录的角色表可能更有意义,而不是使它们成为单独的表。这也使其可以通过管理面板轻松添加其他角色,而不是通过新表和迁移。

然后你可以有一个联接表,允许用户通过单选按钮或复选框属于这些角色中的一个或多个。

用户 - has_and_belongs_to_many:角色
角色 - has_and_belongs_to_many:用户

<legend>Roles</legend>
<div class="form-group">
  <%= f.collection_check_boxes(:role_ids, Role.all, :id, :name, :item_wrapper_class => 'inline') %>
</div>

确保允许:role_ids =&gt; []在你的控制器的user_params