添加条目表仅由父模型ID [英] Add entry to table consisting only of parent model id

查看:89
本文介绍了添加条目表仅由父模型ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型在一个应用程序:导演; 人HAS_ONE主任。一个人可以是很多东西(官员,承包商等,并导演);如果他们是一个导演,我只是想保存自己的用户ID的董事表,仅此而已。

I have two models in an app: Person and Director; person has_one director. A person can be many things (officer, contractor etc AND director); if they are a director I simply want to store their user id in the directors table and nothing more.

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

The table I set up therefore consists only of 4 columns:

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)

我想在窗体上的每个人进入有一个嵌套的单选按钮,如果它被设置为是,创建于董事表中的条目,并删除它是否设置为No/不创建一个条目看似简单,但我意识到,我不知道该怎么做,因为从单选按钮明确的价值将不会被保存到数据库中。

I would like each person entry on a form to have a nested radio button that creates an entry in the directors table if it's set to "Yes" and removes/doesn't create an entry if it's set to "No." Seems simple but I'm realizing I have no idea how to do that, since the explicit value from the radio button wouldn't be saved to the database.

有没有拉这一关好办法?

Is there a good way to pull this off?

推荐答案

您可以添加 attr_accessor ​​模式,如 is_director 。这是将不被存储在数据库中的临时属性。然后根据 is_director 的值,你可以有一个回调来设置逻辑,以用户自己的所长。

You can add an attr_accessor to your Person model, such as is_director. This is a temporary attribute that will not be stored in the database. And then based on the value of is_director, you can have a callback to set the logic to make the user their own 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

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

Then in your form, you can add the radio buttons:

<%= 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 许可在控制器的强烈PARAMS的数组。

You would also need to add is_director to the permit array of the strong params in your controller.

这篇关于添加条目表仅由父模型ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆