数据未保存在连接表中

时间:2015-03-21 05:01:32

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 has-and-belongs-to-many

我正在一个网站上工作,用户可以拥有多个项目,多个用户可以为单个项目做出贡献。 我有一个项目模型

class Project < ActiveRecord::Base
  #associations
  has_and_belongs_to_many :users
end

和用户模型

class User < ActiveRecord::Base
  #associations
  has_and_belongs_to_many :projects
end

我已经用名称创建了一个连接表 - :projects_users 当我在rails控制台上运行代码时,一切正常。 但是当我尝试在控制器中执行保存操作时,数据不会保存在连接表中。 控制器代码

请帮助

class ProjectsController < ApplicationController

 def new
   @project = Project.new
 end

 def create
   @user = User.find(session[:user_id])
   @project = Project.new(project_params)   
     if @project.save
       @project.users << @user
       redirect_to @project
     else 
       flash[:error] = "Project has not been created due to some error"
       render 'new'
     end
 end

  private

  def project_params
    params.require(:project).permit(:name,:description)
  end
end

2 个答案:

答案 0 :(得分:0)

尝试使用nestes_attributes_for

class Answer < ActiveRecord::Base
    belongs_to :question
end


class Question < ActiveRecord::Base
    has_many :answers
    accepts_nested_attributes_for :answers, allow_destroy: true
end

控制器

def new
    @question = Question.new
    @question.answers.build
end

def create
    @question = Question.new(question_params)
    respond_to do |format|
        if @question.save
            format.html { redirect_to @question, notice: 'question was successfully created.' }
            format.json { render action: 'show', status: :created, location: @question }
        else
            format.html { render action: 'new' }
            format.json { render json: @question.errors, status: :unprocessable_entity }
        end
    end
end

def question_params
    params.require(:question).permit(:name, :description, answers_attributes:[:content, :id, :question_id])
end        

你的表格应该是这样的

<%= form_for(@question) do |f| %>
  <% if @question.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@question.errors.count, "error") %> prohibited this question from being saved:</h2>

      <ul>
      <% @question.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>

  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_field :description %>
  </div>

  <%= f.fields_for :answer do |builder| %>
     <%= builder.label :content %>
     <%= builder.text_area :content %>
  <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

答案 1 :(得分:0)

刚刚改变了

@project.users << @user

@user.projects << @project

它开始工作。不知道原因,但它的工作