我有一个问题Problem
模型has_many
。我的问题模型has_many
问题。我有一个名为 的连接表issue_problems
,它有自己的模型,即belongs_to
问题和问题。在我的问题表单中,我试图将问题分配给带有选择标签的问题。(问题已经创建,所以我只是分配给问题。)我已经尝试过了,但收到以下错误:
undefined method `reject' for "3":String
和堆栈错误:
app/controllers/problems_controller.rb:12:in `create'
注意:我计划在未来实施一些允许我分配多个问题以has_many
利用
这是我的代码:
我的问题模型:
class Issue < ActiveRecord::Base
validates :name, :presence => true, :on => :create
has_many :issue_problems
has_many :problems, :through => :issue_problems
end
我的问题模型:
class Problem < ActiveRecord::Base
validates :body, :presence => true
belongs_to :user
has_many :solutions
has_many :issue_problems
has_many :issues, :through => :issue_problems
accepts_nested_attributes_for :solutions, :issues
end
我的问题问题模型:
class IssueProblem < ActiveRecord::Base
belongs_to :problem
belongs_to :issue
end
我对问题控制器的创建操作:
def create
@problem = current_user.problems.new(params[:problem])
@solution = @problem.solutions.new(params[:problem][:solution])
respond_to do |format|
if @problem.save
@problem.issues << @problem.issue
@solution.save!
@solution.update_attributes(problem_id: @problem.id, user_id: current_user.id)
format.html { redirect_to(@problem, :notice => 'Problem was successfully created.') }
format.xml { render :xml => @problem, :status => :created, :location => @problem }
else
format.html { render :action => "new" }
format.xml { render :xml => @problem.errors, :status => :unprocessable_entity }
end
end
end
我的表格:
<%= form_for(@problem) do |f| %>
<%= f.hidden_field :published_at, :value => Time.now %>
<% if @problem.errors.any? %>
<div id="errorExplanation">
<p>Halt! Just so you know, you have to fix these <%= pluralize(@problem.errors.count, "error") %> before you can ask a question:</p>
<ul>
<% @problem.errors.full_messages.each do |msg| %>
<li>- <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="input-container">
<%= f.text_field :body, :placeholder => "What's your problem?" %>
</div>
<%= f.fields_for :solution do |f| %>
<%= f.hidden_field :published_at, :value => Time.now %>
<div class="input-container">
<%= f.text_field :body, :placeholder => "What solution do you propose?" %>
</div>
<% end %>
<%= f.select :issue_ids, Issue.all.collect {|x| [x.name, x.id]}, :prompt => "Select an issue" %>
<div id="button">
<%= f.submit 'Add', :class => 'button' %>
</div>
<% end %>