我使用的模型属于另外两个模型。当我尝试创建它时,我设法获得了两个ID,但内容本身没有存储在数据库中
def create
@person = Person.find(current_person)
@message = Message.create(:group => Group.find(params[:group_id]), :person => Person.find(current_person))
if @message.save
redirect_to(:back)
else
redirect_to(:back)
end
end
<% form_for(:message, :url => messages_path(:person_id => current_person.id, :group_id => @group.id)) do |f| %>
<%= f.text_area :content %>
<%= f.submit "Submit" %>
<%end %>
另外,content
在数据库中被设置为文本,我使用的是PostgreSQL。
@message = Message.create params[:message].merge(:group => Group.find(params[:group_id]), :person => Person.find(current_person))
@为什么上面的答案应该为您做这件事。但你可以更进一步,利用联想的力量。
在你的message.rb中,你会有关联
class Message < ActiveRecord::Base
..
belongs_to :group
belongs_to :person
...
end
在组/个人模型中也可以有类似的关联,它声明了has_many关系。
class Group < ActiveRecord::Base
...
has_many :messages
...
end
class Person < ActiveRecord::Base
...
has_many :messages
...
end
在路由.rb(Rails2.3.x)中
map.resources :group, :has_many => [:messages]
在路由.rb(Rails3)中
resources :groups do
resources :messages
end
这将给你一条类似的路线
POST group_messages_path(:group_id) # => this will route to
# MessagesController's create action
# and provide params[:group_id]
您使用的current_person似乎与当前登录有关,因此通过url或参数使其可见或可编辑不是一个好主意。current_person应该派生自create操作本身中的会话。
# form_for([@group,:message]) or form_for([@group,@message])
# automatically works out the path as POST /groups/:group_id/messages => MessagesController#create
# And current person association remains safe to currently logged in person
# without being revealed thru parameters and such.
<% form_for([@group,@message]) do |f| %>
<%= f.text_area :content %>
<%= f.submit "Submit" %>
<% end %>
def create
@group = Group.find(params[:group_id])
@person = current_person # or however you find current_person
@message = @group.messages.build(params[:messaage])
@message.person = @person
if @message.save
redirect_to(:back)
else
redirect_to(:back)
end
end
尝试更改
@message = Message.create(:group => Group.find(params[:group_id]), :person => Person.find(current_person))
至@message = Message.create(:group => Group.find(params[:group_id]), :person => Person.find(current_person), :content => params[:content]
)