save 2 items in db in 1 controller method(rails )

我的梦境 提交于 2019-12-12 05:39:37

问题


i have a problem with saving 2 items in db at one moment(i am using rails 3.1). I have model Message

class Message < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :content
end

Message model have params: user_id(reciever), user_from(sender), and content(text)

and model User is

class User < ActiveRecord::Base
  has_many :posts
  has_many :messages
end

in MessagesController i have method

 def create
  @message =Message.new(params[:message])


  User.find(@message.user_id).messages.build(params[:message])
  User.find(@message.user_from).messages.build(params[:message])
  end

and the problem is that User.find(@message.user_id) only have this message , user_from dont have. I even have tryed this User.find(2).messages.build(params[:message]) instead of User.find(@message.user_from).messages.build(params[:message]) and user with id 2 dont have this message too, only user with user_id have. what i am doing wrong??

Thanks in advance


回答1:


Use create rather than build.

build is used when you want to create an model instance but don't want to save it immediately. In your case the message instances are being created but not saved.




回答2:


Your message model should have association to both sender and receiver of the message,

class Message < ActiveRecord::Base
  belongs_to :sender
  belongs_to :receiver
  validates_presence_of :content
end

class User < ActiveRecord::Base
  has_many :posts
  has_many :send_messages, :foreign_key => "message_from"
  has_many :received_messages, :foreign_key => "message_id"
end

Also assuming your params will have the message_id(id of message receiver), you should do the following in your controller,

@message = current_user.send_messages.build(params[:message])



回答3:


The model design is not right. How about:

class Message < ActiveRecord::Base
  belongs_to :sender, :class_name => "User"
  belongs_to :receiver, :class_name => "User"
end

class User < ActiveRecord::Base
  has_many :sent_messages, :class_name => "Message", :foreign_key => "sender_id"
  has_many :received_messages, :class_name => "Message", :foreign_key => "receiver_id"
end

And the controller is simple (you need params[:message][:sender_id] and params[:message][:receiver_id] to be set from the form):

def create
  @message = Message.create(params[:message])
  ...
end

But you probably don't want the user to tamper with the sender identity, so:

def create
  @message = current_user.sent_messages.create(params[:message])
  ...
end


来源:https://stackoverflow.com/questions/7944941/save-2-items-in-db-in-1-controller-methodrails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!