在Rails 4.0应用程序中,我有一个表单及其相应的创建操作。它们都很完美:
查看表单
<%= form_for @user_friendship, method: :post do |f| %>
<div class="form form-actions">
<%= f.text_field :friend_id, value: @friend.id %>
<%#= f.button :submit #=> This creates a User_friendship %>
<%= f.button :submit %>
<%= link_to "Cancel", profile_path(@friend.profile_name), class: 'btn' %>
</div>
<% end %>
创建行动
def create
if params[:friend_id]
@friend = User.find_by_id(params[:user_friendship][:friend_id])
logger.fatal "Here is the friend:"
logger.fatal @friend.inspect
else
end
if @friend
@user_friendship = UserFriendship.request(current_user,@friend)
logger.fatal @user_friendship.inspect
# if @user_friendship.new_record?
# flash[:error] = "There was a problem creating that friend request"
# else
# flash[:success] = "Friend request sent to " + @friend.first_name
# end
redirect_to profile_path(@friend.profile_name), status: 302
else
flash[:error] = "Friend required!"
redirect_to root_path, status: 302
end
end
但是当我取消注释这些内容时:
if @user_friendship.new_record?
flash[:error] = "There was a problem creating that friend request"
else
flash[:success] = "Friend request sent to " + @friend.first_name
end
我收到此错误消息:
NoMethodError in UserFriendshipsController#create
undefined method `new_record?' for #<Mail::Message:0x00000104aae768>
我不知道这个错误来自哪里(这是邮件的问题吗?)所以请告诉我是否需要发布更多信息。
我发现Mail::Message
部分真的很奇怪......这个对象是什么?
模型
def self.request(user1, user2)
friendship1 = []
transaction do
friendship1 = create!(user_id: user1.id, friend_id: user2.id, state: 'pending')
friendship2 = create!(user_id: user2.id, friend_id: user1.id, state: 'requested')
end
friendship1.send_request_email
end
def send_request_email
UserNotifier.friend_requested(id).deliver
end
邮件收发器:
def friend_requested(user_friendship_id)
user_friendship = UserFriendship.find(user_friendship_id)
@user = user_friendship.user
@friend = user_friendship.friend
mail to: @friend.email,
subject: @user.first_name + " wants to be your friend!"
end
答案 0 :(得分:1)
好吧,您在UserFriendship.request调用中获取了一个Mail :: Message对象。这个对象有一个方法“new_record?” ?。可能不是。
答案 1 :(得分:1)
@user_friendship
被分配了从调用UserFriendship.request(...)
返回的值。看来该方法返回一个邮件对象(您是在那里发送电子邮件通知作为方法的最后一行吗?)。尝试从该方法返回UserFriendship对象。
编辑:
更好的是,只需执行@user_friendship = UserFriendship.create(current_user, @friend)
然后在after_create回调中发送电子邮件。