开发者

One model and controller but slightly different views and routes in rails3

I have a model Notifications, and it basically handles the same few things. A simple contact form, an invitations form, etc. They all have the same generic items... ie Name, email, comment, blah.

There might be one slightly different field but they are optional, so I'd like to treat them as one model with a differentiating field called: notification_type so Invitation or Feedback, etc. And only render different views which i created in subfolders under notifications (notifications/invitations/).

I have it working fine with something like this in my routes:

routes

resources :notifications
match 'invites' => 'notifications#new', :defaults => { :notification_type => 'invitation' } 

I pass the notification_type...

new.html.erb

<% if params[:notification_开发者_JS百科type] or params[:notification][:notification_type] == "invitation" %>
 <%= render "notifications/invitations/form" %>
<% end %>

form.html.erb

I pass a hidden field for the notification_type

<%= f.input :notification_type, :as => 'hidden', :input_html => { :value => @notification.notification_type ||= params[:notification_type] } %>

It all seems to work.. the only caveat being that if they create an error, it sends them to the /notification route instead of being in invites.. but it still works correctly otherwise but I'm wondering it there's a simpler way to do the same thing? From within the controller layer? I feel like something's going to surprise me later as it stands.


I'd do the inheritance in the model and have two controllers. My controllers are as small as possible so normally I'm ok with adding many of them. But this is a pretty neat solution outside of the form errors. I think your hunch might be right as it gets more complex.

So to be clear, I'd have to models Invitation and Feedback. Each model would set_table_name to "notifications", inherit from Notification and then set the default notification in the initialize method or use the :defaults block you have in your routes already. This is a bit more flexible and explicit imo.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜