1

我有一个问题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>-&nbsp;<%= 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 %>
4

2 回答 2

0

如果您足够开放以观看此链接中的8. 关联 - 多对多部分,那么我认为您对所有内容都足够清楚。

观看 railscasts并从头开始了解所有内容。

编辑:

尽管您的问题已解决,但请将此作为访问此处以深入了解 ROR 中的多对多关联的人们的指针。

于 2012-05-05T15:18:16.280 回答
0

我认为您不需要 IssueProblem 模型。您应该将“has_and_belongs_to_many”放入问题和问题模型中,如下所示:

class Issue < ActiveRecord::Base
  has_and_belongs_to_many :problems
end

class Problem < ActiveRecord::Base
  has_and_belongs_to_many :issues
end
于 2012-05-05T15:10:18.940 回答