【问题标题】:Checked checkboxes only for the users in a project仅为项目中的用户选中复选框
【发布时间】:2013-01-27 02:27:04
【问题描述】:

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

Projects
Users
Project_users <-- members of a project

我正在处理用于编辑项目的视图,其中包含一个包含所有项目字段的表单,并且对于项目的成员,我呈现出复选框。这可行,但使用下面的代码,所有复选框都被选中,即使对于不是项目成员的用户也是如此。

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

编辑项目视图:

<%= 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 %>

项目控制器:

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

【问题讨论】:

    标签: ruby-on-rails database ruby-on-rails-3 checkbox many-to-many


    【解决方案1】:

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

    查看文档: check_box_tag(name, value = "1", checked = false, options = {})

    在你的情况下:

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

    【讨论】:

    • 感谢您的回答!试了一下,得到以下错误:.../edit.html.erb:26: syntax error, unexpected '=' should_be_checked? = project.users.include?(user)
    • 在我将“@”添加到 project.users...(@project.users...)并在控制器中更改为 User.all 后,它起作用了。非常感谢!
    • 不客气,我很高兴能帮上忙!你也应该接受答案;)
    猜你喜欢
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2012-10-15
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多