Domanda

I have users and projects, and I'm trying to create a link to the project by searching for the project using an ActiveRecord call. This is my link_to:

<%= link_to "Project ABC" User.first.projects.where('title' => 'Project ABC') %>

I know that this is not in the routes.rb, so how would I be able to make it so I can do something like this where I write a query to get the project and then show it? Would I do something like:

<%= link_to "Project ABC" show_project_path(User.first.projects.where('title' => 'Project ABC')) %>

If so, would I need anything special in my controller?

È stato utile?

Soluzione

You need to improve understanding of MVC pattern.

Yes the code might work but work is not equal to good. (You missed a comma after first arg but I assume they are misspelling)

View is for present only. It should be dumb without knowing much logic. Like a client sitting in restaurant, View just eat the food without knowing how it cooked.

The MVC way is to prepare such food in Controller and feed View with instance variable(s).

# Controller
def show
  @project = User.projects.whatever
end

# View
<%= link_to "Project ABC", @project %>

Altri suggerimenti

Why not just search by project title?

edit: Billy Chan is right in saying the bulk of this should be moved to the controller.

controller:

@project = User.first.projects.find_by title: 'Project ABC'

view:

<%= link_to "Project ABC" show_project_path(@project) %>

source: http://guides.rubyonrails.org/active_record_querying.html

1.1.5 find_by

Model.find_by finds the first record matching some conditions. For example:

Client.find_by first_name: 'Lifo'
# => #<Client id: 1, first_name: "Lifo">

Client.find_by first_name: 'Jon'
# => nil
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top