开发者

rails wrong association has_many link

Trying to set up very basic association between Customer and Contact model.

Customer has_many :contacts 
Contact belongs_to :customer
User has_many :customers

Routes

    resources :customers do
      resources :contacts
    end

I don't want /contacts to be accessible

When I add in my views

new_customer_contacts_path

I have an error. If I have

new_c开发者_开发知识库ustomer_contact_path(contact)

it works however link to contact#show is wrong --> it directs to customers/7/contact/2 where it should be customers/2/contact/7

Any idea?


new_customer_contact_path(contact)

This is wrong. You should pass customer to it instead of contact.

If you want to show the contact of a customer, you should use customer_contact_path(customer, contact).

For reference, go to http://guides.rubyonrails.org/routing.html and search 'Creating Paths and URLs From Objects'


You gotta tell the customer whose contact belongs_to!

Like the following:

# Customer.first and Contact.first can be exchanged to instances 
# of Customer or Contact!

new_customer_contacts_path(Customer.first)
edit_customer_contact_path(Customer.first, Contact.first)
customer_contacts_path(Customer.first)


With nested routes you need to pass the objects (or at least their ids) in the order they are listed in the route. In the case of 'new' you only need to pass the parent object id as there is no id yet for the new nested object.

new_customer_contact_path(customer)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜