1

私のアプリの簡単な概要。

ユーザーが最初にあるページでセット A クライアントを作成し、次に別のページを使用してジョブを作成してユーザーに割り当てるという点で、これは非常に基本的です。

クライアント モデルとビューは期待どおりに動作していますが、ジョブ モデルをリンクできません。

これが私の仕事のモデルです。

class Client < ActiveRecord::Base 
  has_and_belongs_to_many :jobs
end

class Job < ActiveRecord::Base
  has_and_belongs_to_many :clients
end

ここにも私のクライアントコントローラーがあります。

class JobsController < ApplicationController

  def index
    @jobs = Job.find(:all)

    respond_to do |format|
      format.html # index.html.erb
      format.xml { render :xml => @job }
    end
  end

  def new
    @jobs = Job.new 

    respond_to do |format|
      format.html # index.html.erb
      format.xml { render :xml => @job }
    end
  end

  def create
    @jobs = Job.new(params[:job])
    respond_to do |format|
      if @jobs.save
        format.html { redirect_to @jobs, notice: 'Job was successfully created.' }
        format.json { render json: @jobs, status: :created, location: @jobs }
      else
        format.html { render action: "new" }
        format.json { render json: @jobs.errors, status: :unprocessable_entity }
      end
    end
  end

  def show
    @jobs = Job.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @jobs }
    end
  end
end

私のフォームには 2 つのフィールドがあります。1 つはジョブ名用で、もう 1 つはデータベースにリストされているすべてのクライアントのドロップダウンです。

ただし、これに記入して保存を押すと、次のエラーが表示されます。

ActiveRecord::UnknownAttributeError in JobsController#create

**unknown attribute: client_id**

Application Trace | Framework Trace | Full Trace
app/controllers/jobs_controller.rb:22:in `new'
app/controllers/jobs_controller.rb:22:in `create'
Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"0ZVYpM9vTgY+BI55Y9yJDwCJwrwSgGL9xjHq8dz5OBE=",
 "job"=>{"name"=>"Sample Monthly",
 "client_id"=>"1"},
 "commit"=>"Save Job"}

私はまたと呼ばれるジャンクションテーブルのセットアップを持っていますclients_jobs..

class AddClientsJobsTable < ActiveRecord::Migration
  def up
    create_table :clients_jobs, :id => false do |t|
      t.belongs_to :job, :client
      t.integer :client_id
      t.integer :job_id
  end
end

  def down
    drop_table :clients_jobs
  end
end

宣言する必要があると思いますclient_id

どこかですが、これは私の最初のRailsアプリであり、どこにあるのかわかりません。

どんな助けでも大歓迎です。

編集:これが私の仕事のフォームです。

<%= simple_form_for :job do |f| %>
  <%= f.input :name %>
  <%= select("job", "client_id", Client.all.collect {|c| [ c.name, c.id ] }, {:include_blank => 'None'})%>
  <%= f.button :submit %>
<% end %>
4

1 に答える 1

0

あなたのモデルは仕事を述べています-クライアントはhabtmアソシエーションですが、フォームは仕事が(1つの)クライアントに属しているかのように実装されています。実際にジョブを複数のクライアントに割り当てることが目的である場合、 for は次のようになります。

<%= collection_select(:job, :client_ids, Client.all, :id, :name, {:include_blank => 'None'}, { :multiple => true }) %>

複数の「client_ids」に注意し、入力で複数を許可します。

ジョブが 1 人のユーザーのみに属している場合は、has_and_belongs_to_many :clients を使用しないでください。

于 2012-05-12T01:15:11.710 に答える