我有一个跟踪SAT辅导课程的网站。学生学习的课程是一系列规则。我有一个名为“Sittings”的辅导课程的模型,规则模型称为“规则”。我希望网站管理员能够输入按日期排序,然后使用复选框选择学生在该坐位中出错的“规则”。我有点困惑的是如何创建表单来提取特定规则而不向我的Sitting1 rule1,rule2等模型添加属性。我正在使用simple_form来创建我的表单。
我的坐姿模式:
class Sitting < ActiveRecord::Base
attr_accessible :date, :comment, :rule_id, :user_id
validates :date, presence: true
belongs_to :user
has_many :combos
has_many :rules, :through => :combos
end
我的规则模型:
class Rule < ActiveRecord::Base
attr_accessible :name, :subject, :session_id, :hint_id, :question_id, :trigger_id
validates :name, presence: true
validates :subject, presence: true
has_many :questions
has_many :triggers
has_many :hints
has_many :combos
has_many :sittings, :through => :combos
end
我的组合模型:
class Combo < ActiveRecord::Base
belongs_to :sitting
belongs_to :rule
end
编辑:
这是我为表单尝试的内容。它确实创建了复选框表单,但我的数据库没有更新rule_id。 (当我创建一个坐着时显示为零)
形式:
<%= simple_form_for(@sitting, html: { class: "form-horizontal"}) do |f| %>
<%= f.error_notification %>
<% Rule.all.each do |rule| %>
<%= check_box_tag "sitting[rule_ids][]", rule.id, @sitting.rule_ids.include?(rule.id) %> <%= rule.id %>
<% end %>
<div class="form-group">
<%= f.input :comment, as: :text, input_html: { rows: "2", :class => "form-control" }, label: "Comments:" %>
</div>
<div class="form-group">
<%= f.date_select :date, as: :date, label: "Taken Date:" %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我更新了我的强力参数以允许数组:
def create
@sitting = Sitting.new(sitting_params)
respond_to do |format|
if @sitting.save
format.html { redirect_to @sitting, notice: 'Sitting was successfully created.' }
format.json { render action: 'show', status: :created, location: @sitting }
else
format.html { render action: 'new' }
format.json { render json: @sitting.errors, status: :unprocessable_entity }
end
end
end
def sitting_params
params.require(:sitting).permit(:comment, :date, :user_id, :rule_id => [])
end
我是否遗漏了一些东西才能正确更新Sitting.rule_id?我的日志中出现以下错误:
WARNING: Can't mass-assign protected attributes for Sitting: rule_ids
app/controllers/sittings_controller.rb:27:in `create'
答案 0 :(得分:0)
总结一下我们在聊天中得到的结论。
首先,您不需要同时使用attr_accessible
和strong_params
。我前段时间发布了another answer,解释了这两种方法之间的差异。
你正在运行rails 4,所以你应该利用强大的params而不是使用protected_attributes gem。简而言之,从您的Gemfile以及所有attr_accessible
调用中删除此gem。
正如玛丽安注意到的那样,你的强参数方法中有一个拼写错误,你需要允许rule_ids
,而不是rule_id
。 rule_id
列已过时,为sitting has_many :rules :through
而非sitting belongs_to :rule
- 很可能是旧关联代码的工件。
只要在模型中分配了rule_ids,它就会在连接表中创建新的连接模型,从而在给定的坐标和传递的规则之间创建关联。