当我尝试在 Rails 3 项目中提交表单时出现以下错误。当一个用户使用 Simple Private Messaging 插件向另一个用户发送消息时使用该表单。
我现在设置网站的方式是,用户无需注册或登录即可发送消息。
我得到的错误
NoMethodError in MessagesController#create
undefined method `find_by_login' for #<Class:0x12a374238>
app/controllers/messages_controller.rb:33:in `create'
消息控制器
def new
@message = Message.new
if params[:reply_to]
@reply_to = @user.received_messages.find(params[:reply_to])
unless @reply_to.nil?
@message.to = @reply_to.sender.login
@message.subject = "Re: #{@reply_to.subject}"
@message.body = "\n\n*Original message*\n\n #{@reply_to.body}"
end
end
end
def create
@message = Message.new(params[:message])
@message.sender = @user
@message.recipient = User.find_by_login(params[:message][:to])
if @message.save
flash[:notice] = "Message sent"
redirect_to user_messages_path(@user)
else
render :action => :new
end
end
消息>新视图(这是创建表单的地方)
<%= form_for @message, :url => messages_path(:user_id => @user) do |f| %>
<br>
<br />
<br />
<div class="field">
Hello! My name is <%= f.text_field :subject %> and I'm contacting you in response to your ad. I'm interested in learning more so get in touch! Here's my contact details: <%= f.text_field :body %>.
</div>
<button type="submit" class="btn span6 large">Submit</button>
<% end %>
消息模型
class Message < ActiveRecord::Base
is_private_message
attr_accessor :to
end
用户模型
class User < ActiveRecord::Base
has_many :posts
has_one :profile
has_private_messages
attr_accessible :email
validates_presence_of :email
validates_uniqueness_of :email, :message =>"Hmm, that email's already taken"
validates_format_of :email, :with => /^([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})$/i, :message => "Hi! Please use a valid email"
end
用户迁移
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email
t.string :salt
t.timestamps
end
end
end
通过登录查找用户的 RAILS 控制台输出
>> u = User.first
User Load (1.0ms) SELECT "users".* FROM "users" LIMIT 1
=> nil
>> u.login
NoMethodError: undefined method `login' for nil:NilClass
from /Library/Ruby/Gems/1.8/gems/activesupport-3.1.1/lib/active_support/whiny_nil.rb:48:in `method_missing'
from (irb):2
>>
路线.RB
Mysalary::Application.routes.draw do
resources :users do
resources :messages
end
resources :profiles
resources :pages
resources :posts
get "pages/home"
get "pages/about"
get "pages/legal"
get "pages/feedback"
root :to => 'posts#new'
end