these are my 3 models :
model for User:
class User < ActiveRecord::Base
has_many :patients, through: :treatments
has_many :treatments
.
.
.
model for patient:
class Patient < ActiveRecord::Base
has_many :user, through: :treatments
has_many :treatments, dependent: :destroy
.
.
.
model for treatment:
class Treatment < ActiveRecord::Base
belongs_to :patient
belongs_to :user
validates :patient_id, presence: true
default_scope -> { order(created_at: :desc) }
end
And this is my treatment table :
class CreateTreatments < ActiveRecord::Migration
def change
create_table :treatments do |t|
t.date :teartment_date
t.text :remark
t.float :fee
t.references :patient, index: true, foreign_key: true
t.timestamps null: false
end
add_index :treatments, [:patient_id, :created_at]
end
end
now i want to define a controller to create a new treatment that belongs to a specific user's patient.
this is my controller :
def new
@treat = Treatment.new
end
def create
@userpatient = current_user.treatments.build(treat_params)
if @userpatient.save
flash[:success] = "new treatment added"
redirect_to root_url
else
render 'new'
end
end
but this is the error that i receive, while i want to create a new treatment :
ActiveRecord::UnknownAttributeError in TreatmentsController#create
unknown attribute 'user_id' for Treatment.
and this is the current_user :
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end
i'm new to rails, the basic idea is i want my user to have treatment that belongs to a specific patient.
Thanks to replies i've over come with this issue by adding a reference column . now i receive no, but it does not save any treatments. i mean the part :
if @treat.save
flash[:success] = "new treatment added"
redirect_to root_url
else
render 'new'
end
it does not save and just render 'new' .
i have 2 questions :
1- how can i code my create controller ?
2- how to retrieve my treatments base on patient.what variable should i define in my patient 'show' method to have its treatments retrieved ?
When you say that User
has_many :treatments
and that Treatment
belongs_to :user
, both associations are expecting to find a user_id
column in your treatments
table. You might want to change your migration to include:
t.integer :user_id
and then drop your tables (if they have no data yet!) and rerun the migrations. Alternatively, you could create a new migration and simply run that:
add_column :treatments, :user_id, :integer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.