前提・実現したいこと
プログラミング初学者です。
railsにてUserモデルとCompanyモデル間のリレーションシップを行いました。
※1対多
あるユーザーはCompanyデータを複数持っていて、参照できるのは該当ユーザーのみというものを作成したいと考えております。
発生している問題・エラーメッセージ
NoMethodError in CompaniesController#new undefined method `company' for #<User:0x007f8f13780b78>
該当のソースコード
ruby
1class AddNameToUsers < ActiveRecord::Migration 2 def change 3 add_column :users, :name, :string 4 end 5end 6
class CreateCompanies < ActiveRecord::Migration def change create_table :companies do |t| t.string :nameco t.text :business t.text :recruit t.integer :income t.text :wish t.integer :wishpoint t.integer :employee t.string :advance t.text :remarks t.timestamps end end end
class AddUserToCompany < ActiveRecord::Migration def change add_column :companies, :user_id, :integer end end
class Company < ActiveRecord::Base belongs_to :user validates :user_id, presence: true validates :nameco, :business, presence: true, length: { maximum: 30 } end
class User < ActiveRecord::Base has_many :company , dependent: :destroy validates :name, presence: true, length: { maximum: 50 } # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end
class CompaniesController < ApplicationController before_action :authenticate_user! def new @new=Company.new end def edit end def create @new=current_user.company.build(create_params) if @new.save redirect_to root_url end end def show end private def create_params params.require(:company).permit(:nameco,:business) end end
class UsersController < ApplicationController before_action :authenticate_user! def show @user=User.find(params[:id]) end end
<h2>企業情報登録画面</h2> <%= form_for(@new) do |f| %> <div class="field"> <%= f.label :"企業名" %><br /> <%= f.text_field :nameco %> </div> <div class="field"> <%= f.label :"事業内容" %><br /> <%= f.text_field :business %> </div> <div class="actions"> <%= f.submit "企業情報登録" ,class: "btn btn-lg btn-primary" %> </div> <% end %> <%= link_to "マイページへ戻る" , root_path %>
試したこと
途中は外部キーの設定をしておらず、それが原因かと思いましたが、undefinedということで定義されていないということがどうにもわかりません。
dbをみてもcompanyはありますし、migrateも行っています。
cuurent_userなどを使わず、Companyモデル内だけでのデータ登録はできました。
4時間ほど調べていますが、解決方法がわかっておりません。
どうにか軌道に乗りたいです。
補足情報(FW/ツールのバージョンなど)
ruby 2.0.0
rails 4.0.5
sqlite 1.3.9
あなたの回答
tips
プレビュー