我在rails应用程序中使用devise进行身份验证,并在我的某个控制器中使用'current_user'方法。从那时起,我在User和Activity表之间建立了一个'has_and_belongs_to_many'关联,如下所示。
我的问题是在我的Activities控制器中调用new / create方法时出现以下错误:
'undefined method `user_id' for #<Activity:0x007fe89c4e8400>'
任何人都知道这是由什么引起的? 谢谢!
activities_controller.rb
def create
@activity = Activity.new(params[:activity])
respond_to do |format|
if @activity.save
format.html { redirect_to @activity, notice: 'Activity was successfully created.' }
format.json { render json: @activity, status: :created, location: @activity }
else
format.html { render action: "new" }
format.json { render json: @activity.errors, status: :unprocessable_entity }
end
end
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :name
# attr_accessible :title, :body
#many to many association
has_and_belongs_to_many :activities
end
activity.rb
class Activity < ActiveRecord::Base
attr_accessible :description, :image
validates :description, presence: true
validates :user_id, presence: true
validates_attachment :image, presence: true,
content_type: { content_type: ['image/jpeg', 'image/jpg', 'image/gif', 'image/png']},
size: { less_than: 5.megabytes }
has_and_belongs_to_many :user
has_attached_file :image, styles: { small: "240x180"}
end
schema.rb
ActiveRecord::Schema.define(:version => 20130630004839) do
create_table "activities", :force => true do |t|
t.string "description"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
end
create_table "activities_users", :id => false, :force => true do |t|
t.integer "activity_id"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "name"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
end
答案 0 :(得分:1)
你必须这样做:
@activity = current_user.activities.build(params[:activity])