Reputation: 125
I'm using a model that belongs to 2 other models. When I try to create it, I manage to get both ids, but the content itself isn't stored in database
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 %>
Also, content
is set as text in database and I'm using PostgreSQL.
Upvotes: 1
Views: 124
Reputation: 13433
@why's answer above should do it for you. But you can go a step above and use the power of associations.
In your message.rb, you would have the association
class Message < ActiveRecord::Base
..
belongs_to :group
belongs_to :person
...
end
You could also have a similar association in Group / Person models which declares a has_many relationship.
class Group < ActiveRecord::Base
...
has_many :messages
...
end
class Person < ActiveRecord::Base
...
has_many :messages
...
end
In routes.rb (Rails 2.3.x)
map.resources :group, :has_many => [:messages]
In routes.rb (Rails 3)
resources :groups do
resources :messages
end
This will give you a route like
POST group_messages_path(:group_id) # => this will route to
# MessagesController's create action
# and provide params[:group_id]
You are using current_person which seems to be current login related, so it would not be a good idea to make it visible or editable thru the url or parameters. current_person should be derived from the session in the create action itself.
# 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
Upvotes: 1
Reputation: 9752
Try changing
@message = Message.create(:group => Group.find(params[:group_id]), :person => Person.find(current_person))
to
@message = Message.create(:group => Group.find(params[:group_id]), :person => Person.find(current_person), :content => params[:content]
)
Upvotes: 0
Reputation: 24851
@message = Message.create params[:message].merge(:group => Group.find(params[:group_id]), :person => Person.find(current_person))
Upvotes: 2