【问题标题】:Rails 4: checkbox and has_many throughRails 4:通过复选框和 has_many
【发布时间】:2016-02-18 22:24:53
【问题描述】:

这个例子取自Rails 4 Form: has_many through: checkboxes

型号:

#models/user.rb
class User < ActiveRecord::Base
  has_many :animals, through: :animal_users
  has_many :animal_users
end

#models/animal.rb
class Animal < ActiveRecord::Base
  has_many :users, through: :animal_users
  has_many :animal_users
end

#models/animal_user.rb
class AnimalUser < ActiveRecord::Base
  belongs_to :animal
  belongs_to :user
end

用户表单:

#views/users/_form.html.erb
<%= form_for(@user) do |f| %>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>

  # Checkbox part of the form that now works!
    <div>
      <% Animal.all.each do |animal| %>
        <%= check_box_tag "user[animal_ids][]", animal.id, f.object.animals.include?(animal) %>
        <%= animal.animal_name %>
      <% end %>
    </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

users_controller.rb 中的强参数

 def user_params
    params.require(:user).permit(:name, animal_ids: [])
  end

我按照此示例进行操作,但无法保存连接表。我这里有两个问题

  1. animal_ids、字符串还是整数应该是什么类型?
  2. 如何保存表单?

目前我是这样保存的

def create

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'user was successfully created.' }
        format.json { render json: @user, status: :created, location: @user}
      else
        format.html { render action: "new" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

这只会创建用户而不是连接表。我该怎么做?

【问题讨论】:

  • animal_ids 将是整数数组。其次,您已经编写了@user 的初始化。 @user = User.new(user_params)
  • @usercreate 操作中定义在哪里?
  • 我没有这个初始化并且还在创建用户。我认为在rails4中没关系。 @user = User.new(user_params)。我必须在用户表中为 animal_ids 添加一列吗?

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

@user.save 没有传入嵌套属性 (animal_ids)

您需要像这样传递参数:

@user = User.new(user_params)

在您的用户模型 (user.rb) 中,您需要添加如下内容:

accepts_nested_attributes_for :animals
accepts_nested_attributes_for :animal_users

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 2013-04-26
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 2016-07-24
    相关资源
    最近更新 更多