【问题标题】:Populating Checkboxes on Rails from DB从 DB 填充 Rails 上的复选框
【发布时间】:2011-03-20 10:00:42
【问题描述】:

我刚开始学习 Rails(版本 3),我正在尝试创建一个用户注册表单,其中包含他们感兴趣的复选框选项,可能是 0 个或多个选项。我生成了一个用户脚手架和一个兴趣模型。我在 Postgresql 中为兴趣表播种了数据:

                                 Table "public.interests"
   Column   |            Type             |                       Modifiers
------------+--------------------+------------------------------------------------
 id         | integer                     | not null default nextval('interests_id_seq'::regclass)
 interest   | character varying(40)       |
 created_at | timestamp without time zone |
 updated_at | timestamp without time zone |
Indexes:
    "interests_pkey" PRIMARY KEY, btree (id)

视图有:

<div class="form_row">
    <label for="interest_ids[]">Interests:</label>
    <% for interest in Interest.find(:all) do %>
      <br><%= check_box_tag 'interest_ids[]', interest.id,
              @model.interest_ids.include?(interest.id) %>
      <%= interest.name.humanize %>
    <% end %>
</div>

(基于Checkboxes on Rails

模型interest.rb 有:

class Interest < ActiveRecord::Base
   has_and_belongs_to_many :users
end

用户控制器 users_controller.rb 有:

 def new
  @user = User.new

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @user }
  end
end

当我查看我得到的页面时:

undefined method `interest_ids' for nil:NilClass

谁能告诉我怎么了?谢谢。

【问题讨论】:

  • @model 应该是什么?我没有看到它在任何地方定义。看起来可能应该是 @user 代替?另一个问题是您使用的是 HABTM,最好使用 Has Many Through。
  • 一些问题: 1. 您显示的视图是针对哪个控制器的?我想它是针对 InterestsController.2 的。您的变量@model 应该是哪种类型?在视图中@model得到消息interest_ids,如果@model没有填写,则自动为nil。那应该解释错误消息。一些模型类必须实现interest_ids
  • 这个位 @model.interest_ids.include?(interest.id) %&gt; 帮助我解决了我的问题!我的表单没有重新加载设置或正确保存它们。所以,谢谢:)

标签: ruby-on-rails


【解决方案1】:

你看过 Railscast 吗? http://railscasts.com/episodes/17-habtm-checkboxes

乍一看,如果这些复选框是您使用创建或编辑表单的一部分,我认为标签应该是:

<%= check_box_tag 'user[interest_ids][]', interest.id, @model.interest_ids.include?(interest.id)%>

【讨论】:

    猜你喜欢
    • 2016-09-23
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多