仅选中项目中用户的复选框

时间:2021-09-11 03:37:33

In my database I have two tables that has a many-to-many relationship, and by that reason I've created a relationship table.

在我的数据库中,我有两个具有多对多关系的表,因此我创建了一个关系表。

Projects
Users
Project_users <-- members of a project

I'm working on the view for editing a project, which contain of a form with all the project fields, and for the members of a project I render out checkboxes. This works, but with the code below all the checkboxes is checked, even for the users that's not members of the project.

我正在编写一个用于编辑项目的视图,该项目包含一个包含所有项目字段的表单,而对于项目成员,我则用于复选框。这是有效的,但是使用下面的代码检查所有复选框,即使对于不是项目成员的用户也是如此。

So, how should I change the code so only the checkboxes for the current members of the project gets checked?

那么,我应该如何更改代码,以便只检查项目当前成员的复选框?

edit project view:

编辑项目视图:

<%= form_for @project do |f| %>
    ...
        the rest of the form
    ...
    <div class="checkbox">
        <% @members.each do |user| %>
            <%= check_box_tag "project[members][]", user.id, '1', :id => "user_#{user.id}" %> 
            <%= label_tag "user_#{user.id}", user.first_name + ' ' + user.last_name, :class => "checkbox" %>
        <% end %>
    </div>
    ...
        the rest of the form
    ...
<% end %>

projects controller:

项目控制人:

...
def edit
    @project = Project.find(params[:id])
    @members = @project.users
end
...

1 个解决方案

#1


1  

The third argument to the check_box_tag is the boolean for the check(ed) state:

check_box_tag的第三个参数是check(ed)状态的布尔值:

See the doc: check_box_tag(name, value = "1", checked = false, options = {})

请参阅doc:check_box_tag(name,value =“1”,checked = false,options = {})

In your case:

在你的情况下:

<% should_be_checked = @project.users.include?(user) %>
<%= check_box_tag "project[members][]", user.id, should_be_checked, :id => "user_#{user.id}" %>

#1


1  

The third argument to the check_box_tag is the boolean for the check(ed) state:

check_box_tag的第三个参数是check(ed)状态的布尔值:

See the doc: check_box_tag(name, value = "1", checked = false, options = {})

请参阅doc:check_box_tag(name,value =“1”,checked = false,options = {})

In your case:

在你的情况下:

<% should_be_checked = @project.users.include?(user) %>
<%= check_box_tag "project[members][]", user.id, should_be_checked, :id => "user_#{user.id}" %>